> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Run.cancel() `.cancel()` 方法会取消 workflow run、停止执行并清理资源。 此方法会中止所有正在运行的步骤,并将 workflow 状态更新为 'canceled'。它既适用于正在执行的 workflow,也适用于已暂停或正在等待的 workflow。 ## 使用示例 ```typescript const run = await workflow.createRun() await run.cancel() // Returns: { message: 'Workflow run canceled' } ``` ## 参数 **无参数** (`void`): 此方法不接受任何参数 ## 返回值 **result** (`Promise<{ message: string }>`): 取消成功时,解析为 { message: 'Workflow run canceled' } 的 promise ## 取消的工作原理 调用此方法时,workflow 将: 1. **触发中止信号** - 使用标准 Web API AbortSignal 通知正在运行的步骤 2. **阻止后续步骤** - 不再执行任何后续步骤 ## 中止信号的行为 检查 `abortSignal` 参数的步骤可以响应取消操作: - 步骤可以监听 'abort' 事件:`abortSignal.addEventListener('abort', callback)` - 步骤可以检查是否已经中止:`if (abortSignal.aborted) { ... }` - 可用于取消超时、网络请求或长时间运行的操作 步骤必须主动检查中止信号,才能在执行过程中被取消;否则,当前步骤会运行至完成,但后续步骤不会执行。 ## 扩展使用示例 ### 发生错误时取消 workflow ```typescript const run = await workflow.createRun() try { const result = await run.start({ inputData: { value: 'initial data' } }) } catch (error) { await run.cancel() } ``` ### 创建响应取消操作的步骤 ```typescript 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 } }, }) ``` ## 相关内容 - [Workflows 概览](https://mastra.zisheng.pro/docs/workflows/overview) - [Workflow.createRun()](https://mastra.zisheng.pro/reference/workflows/workflow-methods/create-run)