跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

Run.cancel()

The .cancel() method cancels a workflow run, stopping execution and cleaning up resources.

This method aborts any running steps and updates the workflow status to 'canceled'. It works for both actively running workflows and suspended/waiting workflows.

Usage example
Usage example的直接链接

const run = await workflow.createRun()

await run.cancel()

Parameters
Parameters的直接链接

No parameters:

void
This method takes no parameters

Returns
Returns的直接链接

result:

Promise<void>
A promise that resolves once cancellation is requested and, if storage is configured, the status update to canceled has been attempted. It does not wait for running steps to stop. Calling cancel() on a run that already finished leaves its status unchanged, except with the Inngest engine.

How cancellation works
How cancellation works的直接链接

When called, the workflow will:

  1. Trigger the abort signal - Uses the standard Web API AbortSignal to notify running steps
  2. Prevent subsequent steps - No further steps will be executed

Abort signal behavior
Abort signal behavior的直接链接

Steps that check the abortSignal parameter can respond to cancellation:

  • Steps can listen to the 'abort' event: abortSignal.addEventListener('abort', callback)
  • Steps can check if already aborted: if (abortSignal.aborted) { ... }
  • Useful for cancelling timeouts, network requests, or long-running operations

Steps must actively check the abort signal to be canceled mid-execution; otherwise, the current step runs to completion and subsequent steps don't execute.

Extended usage examples
Extended usage examples的直接链接

Cancelling a workflow on error
Cancelling a workflow on error的直接链接

const run = await workflow.createRun()

try {
const result = await run.start({ inputData: { value: 'initial data' } })
} catch (error) {
await run.cancel()
}

Creating a step that responds to cancellation
Creating a step that responds to cancellation的直接链接

const step = createStep({
id: 'long-running-step',
execute: async ({ inputData, abortSignal, abort }) => {
const timeout = new Promise(resolve => {
const timer = setTimeout(() => resolve('done'), 10000)

// Clean up if canceled
abortSignal.addEventListener('abort', () => {
clearTimeout(timer)
resolve('canceled')
})
})

const result = await timeout

// Check if aborted after async operation
if (abortSignal.aborted) {
return abort() // Stop execution
}

return { result }
},
})