{"record":{"id":"8383d37a36aa8d73","repo":"mastra-ai/mastra","slug":"task-has-not-been-dispatched-yet","errorCode":null,"errorMessage":"Task has not been dispatched yet","messagePattern":"Task has not been dispatched yet","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/core/src/background-tasks/create.ts","lineNumber":44,"sourceCode":" *     onResult: (params) => messageList.addToolResult(params),\n *   },\n * });\n *\n * const { task, fallbackToSync } = await bgTask.dispatch();\n * const completed = await bgTask.waitForCompletion();\n * await bgTask.cancel();\n * ```\n */\nexport function createBackgroundTask(\n  manager: BackgroundTaskManager,\n  options: CreateBackgroundTaskOptions,\n): BackgroundTaskHandle {\n  const { context, ...payload } = options;\n  let taskId: string | undefined;\n\n  return {\n    get task() {\n      if (!taskId) throw new Error('Task has not been dispatched yet');\n      // Synchronous access to task ID — full task data requires async getTask()\n      return { id: taskId } as any;\n    },\n\n    async dispatch() {\n      const result = await manager.enqueue(payload, context);\n      taskId = result.task.id;\n      return result;\n    },\n\n    async checkIfSuspended(args: CheckIfSuspendedPayload) {\n      const result = await manager.listTasks({\n        toolCallId: args.toolCallId,\n        runId: args.runId,\n        agentId: args.agentId,\n        threadId: args.threadId,\n        resourceId: args.resourceId,\n        toolName: args.toolName,","sourceCodeStart":26,"sourceCodeEnd":62,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/background-tasks/create.ts#L26-L62","documentation":"Thrown by the synchronous `task` getter of a BackgroundTaskHandle when the handle has not been dispatched. The handle stores the task ID in a closure variable that is only set inside `dispatch()`; reading `handle.task` before dispatching means no ID exists yet, so the getter throws instead of returning a bogus task object.","triggerScenarios":"Accessing `handle.task` (or `.task.id`) on a handle returned by the background-task create function before calling `await handle.dispatch()`.","commonSituations":"Reading the task ID immediately after creating the handle and forgetting to dispatch; using the getter in a render/log statement before the dispatch promise resolves; assuming `create` itself enqueues the task when it only builds the handle.","solutions":["Call `await handle.dispatch()` before reading `handle.task`.","If you need the ID without dispatching, restructure to dispatch first and then use the returned ID.","Track the dispatched ID yourself from `dispatch()`'s result and pass it where needed instead of reading the sync getter."],"exampleFix":"// before\nconst handle = createBackgroundTask(options);\nconsole.log(handle.task.id); // throws\n\n// after\nconst handle = createBackgroundTask(options);\nawait handle.dispatch();\nconsole.log(handle.task.id);","handlingStrategy":"try-catch","validationCode":"// before reading the sync getter\nlet dispatched = false;\nconst handle = createBackgroundTask(options);\nawait handle.dispatch();\ndispatched = true;\nif (dispatched) console.log(handle.task.id);","typeGuard":"function isDispatched(handle: { task?: { id: string } }): boolean {\n  try {\n    return typeof handle.task?.id === 'string';\n  } catch {\n    return false;\n  }\n}","tryCatchPattern":"let taskId: string | undefined;\ntry {\n  taskId = handle.task.id;\n} catch (err) {\n  if (err instanceof Error && err.message === 'Task has not been dispatched yet') {\n    await handle.dispatch();\n    taskId = handle.task.id;\n  } else throw err;\n}","preventionTips":["Always await dispatch() immediately after creating a background task handle.","Never read handle.task in render paths that run before dispatch resolves.","Keep the ID from dispatch()'s result as your source of truth."],"tags":["background-tasks","lifecycle","dispatch"],"backgroundTag":"task-not-dispatched","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}