Skip to content

AbortController 已中止的 fetch

快速摘要

你在 fetch 落定前调用了 controller.abort()——Promise 以 AbortError reject,永远收不到响应。

为什么发生

  • 在 fetch Promise 落定前调用 controller.abort()

  • 对多个顺序 fetch 复用同一 AbortController

  • 卸载时中止但 fetch 已完成又再次中止

最小示例

✗ 错误代码
const ctrl = new AbortController();
ctrl.abort();
fetch('/api', { signal: ctrl.signal })
  .catch(err => console.error(err)); // AbortError — already aborted
✓ 修复代码
const ctrl = new AbortController();
fetch('/api', { signal: ctrl.signal })
  .catch(err => { if (err.name !== 'AbortError') console.error(err); });
// ctrl.abort() only when you actually want to cancel

fetch 前中止会立即以 AbortError reject。仅在确要取消时才中止,并在 catch 中忽略 AbortError。

如何诊断

  • 在 catch 中检查 err.name === 'AbortError'

  • 调用 fetch 前记录 signal.aborted 值

  • 需要独立中止时为每个 fetch 用新 AbortController

如何修复

  • 为每个可能独立中止的 fetch 创建新 AbortController

  • 调用 fetch 前检查 signal.aborted,已中止则跳过

  • 在 catch 中忽略 AbortError,因为它是预期行为

如何预防

  • 每个 fetch 生命周期用一个 controller

  • 始终在 fetch catch 中优雅处理 AbortError

相关资源

相关术语

相关课程

  • HTTP

    学习 fetch 与 AbortController。

← 返回语言