> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Run.cancel() `.cancel()` 方法會取消 Workflow run、停止執行並清理資源。 此方法會中止所有執行中的步驟,並將 Workflow 狀態更新為 'canceled'。無論 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/zh-TW/docs/workflows/overview) - [Workflow.createRun()](https://mastra.zisheng.pro/zh-TW/reference/workflows/workflow-methods/create-run)