首页 文章 精选 留言 我的

精选列表

搜索[javascript引擎],共10000篇文章
优秀的个人博客,低调大师

JavaScript 中的 AbortController:如何优雅地取消 fetch 请求与清理副作用

在单页应用里,用户快速切换路由、连续触发搜索或者重复提交表单时,发出去的异步请求往往已经不再需要了。浏览器虽然会继续接收响应,但回调里执行的状态更新可能覆盖掉最新的结果,甚至对已经卸载的组件执行 setState,造成内存泄漏或界面闪烁。过去我们用 XMLHttpRequest 的 abort 方法,或者引入 axios 的 CancelToken,现在浏览器原生提供了 AbortController 和 AbortSignal,可以统一取消 fetch、监听事件流以及清理各种异步副作用。这篇文章不堆砌 API 列表,而是从实际开发中常见的搜索框竞态、组件卸载后清理、超时控制这几个场景出发,说明 AbortController 的工作机制、和 fetch 配合时的注意点,以及如何用同一个 signal 管理多个异步操作,最后给出几个容易踩坑的细节。 ## 搜索框竞态:为什么后发请求不一定先到 搜索建议是 AbortController 最典型的用武之地。用户在输入框里连续敲入字母,每次 input 事件都发送一次请求,但服务端处理速度和网络延迟不同,先发出的请求完全可能后返回。如果不做处理,输入框里显示的就是旧关键词的结果。 ```js const input = document.querySelector('#search') let controller = null input.addEventListener('input', async (e) => { const keyword = e.target.value.trim() if (!keyword) return // 取消上一次还没完成的请求 if (controller) controller.abort() controller = new AbortController() try { const res = await fetch(`/api/suggest?q=${encodeURIComponent(keyword)}`, { signal: controller.signal }) const data = await res.json() renderSuggestions(data) } catch (err) { if (err.name === 'AbortError') { // 主动取消,属于预期行为,不提示用户 return } showErrorMessage(err) } }) ``` 这段代码里每次输入都新建一个 controller,abort 之前那个。fetch 收到已经 abort 的 signal 时会立刻 reject 一个 DOMException,name 是 AbortError。这里的关键是不要把所有错误都当成网络异常弹给用户,AbortError 需要单独识别并安静地忽略。 ## 组件卸载时清理,避免更新已销毁的视图 React 或 Vue 组件里,请求发出后组件被卸载是常有的事。如果没有取消,响应回来时执行 setState 或修改 ref,轻则报 warning,重则内存泄漏。把 signal 和组件生命周期绑定起来,卸载时 abort 掉所有挂起的请求。 以 React 为例: ```jsx import { useEffect, useState } from 'react' function UserProfile({ userId }) { const [user, setUser] = useState(null) useEffect(() => { const controller = new AbortController() fetch(`/api/users/${userId}`, { signal: controller.signal }) .then(res => res.json()) .then(setUser) .catch(err => { if (err.name !== 'AbortError') console.error(err) }) return () => controller.abort() }, [userId]) if (!user) return 加载中… return {user.name} } ``` useEffect 的清理函数在 userId 变化或组件卸载时都会执行,controller.abort() 会取消当前请求。这样即使用户快速切换用户 ID,也不会出现旧用户数据覆盖新用户数据的情况。 ## 超时控制:AbortController 和 setTimeout 组合 fetch 本身没有 timeout 选项,用 AbortController 可以自己实现。常见做法是设一个定时器,到时间就 abort。 ```js function fetchWithTimeout(url, options = {}, timeout = 5000) { const controller = new AbortController() const timer = setTimeout(() => controller.abort(), timeout) return fetch(url, { ...options, signal: controller.signal }) .finally(() => clearTimeout(timer)) } fetchWithTimeout('/api/slow', {}, 3000) .then(res => res.json()) .catch(err => { if (err.name === 'AbortError') { console.warn('请求超时或被取消') } }) ``` 需要注意的是,超时引起的 abort 和用户主动取消引起的 abort 在错误里都表现为 AbortError,如果业务上要区分,得自己加标记,比如在 abort 之前往 controller 上挂一个 reason,或者用 AbortSignal.timeout()(较新的 API,目前 Chrome、Firefox、Safari 都已支持)。 ```js fetch('/api/slow', { signal: AbortSignal.timeout(3000) }) ``` AbortSignal.timeout() 返回的 signal 在超时后会自动 abort,并且抛出的错误是 TimeoutError,比手动 setTimeout 更清晰。 ## 同一个 signal 管理多个请求 AbortController 的 signal 可以同时传给多个 fetch,一次 abort 全部取消。在页面级组件里,可以把一个 controller 实例通过 context 或 props 传下去,子组件发请求时共用这个 signal。 ```js const controller = new AbortController() Promise.all([ fetch('/api/a', { signal: controller.signal }), fetch('/api/b', { signal: controller.signal }), fetch('/api/c', { signal: controller.signal }) ]).then(([a, b, c]) => { // 处理结果 }) // 某个时机统一取消 controller.abort() ``` 这样比维护多个取消令牌简单得多。不过要留意,一个请求被 abort 后,Promise.all 会立刻 reject,其他请求虽然也被 abort 了,但它们的 reject 如果不处理,可能在控制台留下未捕获的 Promise 警告。给每个 fetch 单独 catch,或者用 Promise.allSettled 会更稳。 ## 事件监听里的 signal AbortSignal 不仅可以取消 fetch,还能移除事件监听。addEventListener 的第三个参数可以传 `{ signal }`,abort 时监听器自动移除,不用再手动 removeEventListener。 ```js const controller = new AbortController() window.addEventListener('resize', onResize, { signal: controller.signal }) window.addEventListener('scroll', onScroll, { signal: controller.signal }) // 组件卸载或逻辑结束时 controller.abort() ``` 这个特性在封装弹窗、绘图工具或第三方库初始化时很好用,把多个监听器绑定到同一个 signal 上,清理代码只需要一行。 ## 几个容易忽略的细节 fetch 的 signal 只能在请求发出前或响应体读取前生效。如果响应已经返回,正在读取 body,此时 abort 会中断 body 的读取,抛出的错误同样是 AbortError。所以不要以为 res.json() 已经开始了就没法取消。 另外,AbortController 一旦 abort,就永久处于 aborted 状态,不能复用。需要新请求时得创建新的 controller。有些库(比如 axios)内部用 CancelToken,现在也支持传入 signal,但和 fetch 的行为略有差异,混用时注意看文档。 在 Node.js 里,从 v15 开始也支持 AbortController,可以取消 fs 操作、http 请求等。如果写的是同构代码,signal 的处理方式基本一致。 最后,不要在每个略大的异步操作上都无脑加 AbortController,先判断这个操作是否真的可能产生竞态或需要提前终止。过度使用会让代码里到处是 try/catch 和 AbortError 判断,反而降低可读性。只在用户可感知、可重复触发、且结果有状态覆盖风险的地方用它,收益最明显。 推荐查看天气:http://www.362tq.com/qilian/40tian.html 推荐查看天气:http://www.362tq.com/haiyan/ 推荐查看天气:http://www.362tq.com/haiyan/zuotian.html 推荐查看天气:http://www.362tq.com/haiyan/7tian.html 推荐查看天气:http://www.362tq.com/haiyan/10tian.html 推荐查看天气:http://www.362tq.com/haiyan/15tian.html 推荐查看天气:http://www.362tq.com/haiyan/40tian.html 推荐查看天气:http://www.362tq.com/gangcha/ 推荐查看天气:http://www.362tq.com/gangcha/zuotian.html 推荐查看天气:http://www.362tq.com/gangcha/7tian.html 推荐查看天气:http://www.362tq.com/gangcha/10tian.html 推荐查看天气:http://www.362tq.com/gangcha/15tian.html 推荐查看天气:http://www.362tq.com/gangcha/40tian.html 推荐查看天气:http://www.362tq.com/huangnan/ 推荐查看天气:http://www.362tq.com/huangnan/zuotian.html 推荐查看天气:http://www.362tq.com/huangnan/7tian.html 推荐查看天气:http://www.362tq.com/huangnan/10tian.html 推荐查看天气:http://www.362tq.com/huangnan/15tian.html 推荐查看天气:http://www.362tq.com/huangnan/40tian.html 推荐查看天气:http://www.362tq.com/tongrenxian/ 推荐查看天气:http://www.362tq.com/tongrenxian/zuotian.html 推荐查看天气:http://www.362tq.com/tongrenxian/7tian.html 推荐查看天气:http://www.362tq.com/tongrenxian/10tian.html 推荐查看天气:http://www.362tq.com/tongrenxian/15tian.html 推荐查看天气:http://www.362tq.com/tongrenxian/40tian.html 推荐查看天气:http://www.362tq.com/jianzha/ 推荐查看天气:http://www.362tq.com/jianzha/zuotian.html 推荐查看天气:http://www.362tq.com/jianzha/7tian.html 推荐查看天气:http://www.362tq.com/jianzha/10tian.html 推荐查看天气:http://www.362tq.com/jianzha/15tian.html 推荐查看天气:http://www.362tq.com/jianzha/40tian.html 推荐查看天气:http://www.362tq.com/zeku/ 推荐查看天气:http://www.362tq.com/zeku/zuotian.html 推荐查看天气:http://www.362tq.com/zeku/7tian.html 推荐查看天气:http://www.362tq.com/zeku/10tian.html 推荐查看天气:http://www.362tq.com/zeku/15tian.html 推荐查看天气:http://www.362tq.com/zeku/40tian.html 推荐查看天气:http://www.362tq.com/henanxian/ 推荐查看天气:http://www.362tq.com/henanxian/zuotian.html 推荐查看天气:http://www.362tq.com/henanxian/7tian.html 推荐查看天气:http://www.362tq.com/henanxian/10tian.html 推荐查看天气:http://www.362tq.com/henanxian/15tian.html 推荐查看天气:http://www.362tq.com/henanxian/40tian.html 推荐查看天气:http://www.362tq.com/hainanzhou/ 推荐查看天气:http://www.362tq.com/hainanzhou/zuotian.html 推荐查看天气:http://www.362tq.com/hainanzhou/7tian.html 推荐查看天气:http://www.362tq.com/hainanzhou/10tian.html 推荐查看天气:http://www.362tq.com/hainanzhou/15tian.html 推荐查看天气:http://www.362tq.com/hainanzhou/40tian.html 推荐查看天气:http://www.362tq.com/gonghe/ 推荐查看天气:http://www.362tq.com/gonghe/zuotian.html 推荐查看天气:http://www.362tq.com/gonghe/7tian.html 推荐查看天气:http://www.362tq.com/gonghe/10tian.html 推荐查看天气:http://www.362tq.com/gonghe/15tian.html 推荐查看天气:http://www.362tq.com/gonghe/40tian.html 推荐查看天气:http://www.362tq.com/tongde/ 推荐查看天气:http://www.362tq.com/tongde/zuotian.html 推荐查看天气:http://www.362tq.com/tongde/7tian.html 推荐查看天气:http://www.362tq.com/tongde/10tian.html 推荐查看天气:http://www.362tq.com/tongde/15tian.html 推荐查看天气:http://www.362tq.com/tongde/40tian.html 推荐查看天气:http://www.362tq.com/guide/ 推荐查看天气:http://www.362tq.com/guide/zuotian.html 推荐查看天气:http://www.362tq.com/guide/7tian.html 推荐查看天气:http://www.362tq.com/guide/10tian.html 推荐查看天气:http://www.362tq.com/guide/15tian.html 推荐查看天气:http://www.362tq.com/guide/40tian.html 推荐查看天气:http://www.362tq.com/xinghai/ 推荐查看天气:http://www.362tq.com/xinghai/zuotian.html 推荐查看天气:http://www.362tq.com/xinghai/7tian.html 推荐查看天气:http://www.362tq.com/xinghai/10tian.html 推荐查看天气:http://www.362tq.com/xinghai/15tian.html 推荐查看天气:http://www.362tq.com/xinghai/40tian.html 推荐查看天气:http://www.362tq.com/guinan/ 推荐查看天气:http://www.362tq.com/guinan/zuotian.html 推荐查看天气:http://www.362tq.com/guinan/7tian.html 推荐查看天气:http://www.362tq.com/guinan/10tian.html 推荐查看天气:http://www.362tq.com/guinan/15tian.html 推荐查看天气:http://www.362tq.com/guinan/40tian.html 推荐查看天气:http://www.362tq.com/guoluo/ 推荐查看天气:http://www.362tq.com/guoluo/zuotian.html 推荐查看天气:http://www.362tq.com/guoluo/7tian.html 推荐查看天气:http://www.362tq.com/guoluo/10tian.html 推荐查看天气:http://www.362tq.com/guoluo/15tian.html 推荐查看天气:http://www.362tq.com/guoluo/40tian.html 推荐查看天气:http://www.362tq.com/maqin/ 推荐查看天气:http://www.362tq.com/maqin/zuotian.html 推荐查看天气:http://www.362tq.com/maqin/7tian.html 推荐查看天气:http://www.362tq.com/maqin/10tian.html 推荐查看天气:http://www.362tq.com/maqin/15tian.html 推荐查看天气:http://www.362tq.com/maqin/40tian.html 推荐查看天气:http://www.362tq.com/banma/ 推荐查看天气:http://www.362tq.com/banma/zuotian.html 推荐查看天气:http://www.362tq.com/banma/7tian.html 推荐查看天气:http://www.362tq.com/banma/10tian.html 推荐查看天气:http://www.362tq.com/banma/15tian.html 推荐查看天气:http://www.362tq.com/banma/40tian.html 推荐查看天气:http://www.362tq.com/gande/ 推荐查看天气:http://www.362tq.com/gande/zuotian.html 推荐查看天气:http://www.362tq.com/gande/7tian.html 推荐查看天气:http://www.362tq.com/gande/10tian.html 推荐查看天气:http://www.362tq.com/gande/15tian.html 推荐查看天气:http://www.362tq.com/gande/40tian.html 推荐查看天气:http://www.362tq.com/dari/ 推荐查看天气:http://www.362tq.com/dari/zuotian.html 推荐查看天气:http://www.362tq.com/dari/7tian.html 推荐查看天气:http://www.362tq.com/dari/10tian.html 推荐查看天气:http://www.362tq.com/dari/15tian.html 推荐查看天气:http://www.362tq.com/dari/40tian.html 推荐查看天气:http://www.362tq.com/jiuzhi/ 推荐查看天气:http://www.362tq.com/jiuzhi/zuotian.html 推荐查看天气:http://www.362tq.com/jiuzhi/7tian.html 推荐查看天气:http://www.362tq.com/jiuzhi/10tian.html 推荐查看天气:http://www.362tq.com/jiuzhi/15tian.html 推荐查看天气:http://www.362tq.com/jiuzhi/40tian.html 推荐查看天气:http://www.362tq.com/maduo/ 推荐查看天气:http://www.362tq.com/maduo/zuotian.html 推荐查看天气:http://www.362tq.com/maduo/7tian.html 推荐查看天气:http://www.362tq.com/maduo/10tian.html 推荐查看天气:http://www.362tq.com/maduo/15tian.html 推荐查看天气:http://www.362tq.com/maduo/40tian.html 推荐查看天气:http://www.362tq.com/yushu/ 推荐查看天气:http://www.362tq.com/yushu/zuotian.html 推荐查看天气:http://www.362tq.com/yushu/7tian.html 推荐查看天气:http://www.362tq.com/yushu/10tian.html 推荐查看天气:http://www.362tq.com/yushu/15tian.html 推荐查看天气:http://www.362tq.com/yushu/40tian.html 推荐查看天气:http://www.362tq.com/zaduo/ 推荐查看天气:http://www.362tq.com/zaduo/zuotian.html 推荐查看天气:http://www.362tq.com/zaduo/7tian.html 推荐查看天气:http://www.362tq.com/zaduo/10tian.html 推荐查看天气:http://www.362tq.com/zaduo/15tian.html 推荐查看天气:http://www.362tq.com/zaduo/40tian.html 推荐查看天气:http://www.362tq.com/chenduo/ 推荐查看天气:http://www.362tq.com/chenduo/zuotian.html 推荐查看天气:http://www.362tq.com/chenduo/7tian.html 推荐查看天气:http://www.362tq.com/chenduo/10tian.html 推荐查看天气:http://www.362tq.com/chenduo/15tian.html 推荐查看天气:http://www.362tq.com/chenduo/40tian.html 推荐查看天气:http://www.362tq.com/zhiduo/ 推荐查看天气:http://www.362tq.com/zhiduo/zuotian.html 推荐查看天气:http://www.362tq.com/zhiduo/7tian.html 推荐查看天气:http://www.362tq.com/zhiduo/10tian.html 推荐查看天气:http://www.362tq.com/zhiduo/15tian.html 推荐查看天气:http://www.362tq.com/zhiduo/40tian.html 推荐查看天气:http://www.362tq.com/nanqian/ 推荐查看天气:http://www.362tq.com/nanqian/zuotian.html 推荐查看天气:http://www.362tq.com/nanqian/7tian.html 推荐查看天气:http://www.362tq.com/nanqian/10tian.html 推荐查看天气:http://www.362tq.com/nanqian/15tian.html 推荐查看天气:http://www.362tq.com/nanqian/40tian.html 推荐查看天气:http://www.362tq.com/qumalai/ 推荐查看天气:http://www.362tq.com/qumalai/zuotian.html 推荐查看天气:http://www.362tq.com/qumalai/7tian.html 推荐查看天气:http://www.362tq.com/qumalai/10tian.html 推荐查看天气:http://www.362tq.com/qumalai/15tian.html 推荐查看天气:http://www.362tq.com/qumalai/40tian.html 推荐查看天气:http://www.362tq.com/haixi/ 推荐查看天气:http://www.362tq.com/haixi/zuotian.html 推荐查看天气:http://www.362tq.com/haixi/7tian.html 推荐查看天气:http://www.362tq.com/haixi/10tian.html 推荐查看天气:http://www.362tq.com/haixi/15tian.html 推荐查看天气:http://www.362tq.com/haixi/40tian.html 推荐查看天气:http://www.362tq.com/geermu/ 推荐查看天气:http://www.362tq.com/geermu/zuotian.html 推荐查看天气:http://www.362tq.com/geermu/7tian.html 推荐查看天气:http://www.362tq.com/geermu/10tian.html 推荐查看天气:http://www.362tq.com/geermu/15tian.html 推荐查看天气:http://www.362tq.com/geermu/40tian.html 推荐查看天气:http://www.362tq.com/delingha/ 推荐查看天气:http://www.362tq.com/delingha/zuotian.html 推荐查看天气:http://www.362tq.com/delingha/7tian.html 推荐查看天气:http://www.362tq.com/delingha/10tian.html 推荐查看天气:http://www.362tq.com/delingha/15tian.html 推荐查看天气:http://www.362tq.com/delingha/40tian.html 推荐查看天气:http://www.362tq.com/wulan/ 推荐查看天气:http://www.362tq.com/wulan/zuotian.html 推荐查看天气:http://www.362tq.com/wulan/7tian.html 推荐查看天气:http://www.362tq.com/wulan/10tian.html 推荐查看天气:http://www.362tq.com/wulan/15tian.html 推荐查看天气:http://www.362tq.com/wulan/40tian.html 推荐查看天气:http://www.362tq.com/dulan/ 推荐查看天气:http://www.362tq.com/dulan/zuotian.html 推荐查看天气:http://www.362tq.com/dulan/7tian.html 推荐查看天气:http://www.362tq.com/dulan/10tian.html 推荐查看天气:http://www.362tq.com/dulan/15tian.html 推荐查看天气:http://www.362tq.com/dulan/40tian.html 推荐查看天气:http://www.362tq.com/tianjun/ 推荐查看天气:http://www.362tq.com/tianjun/zuotian.html 推荐查看天气:http://www.362tq.com/tianjun/7tian.html 推荐查看天气:http://www.362tq.com/tianjun/10tian.html 推荐查看天气:http://www.362tq.com/tianjun/15tian.html 推荐查看天气:http://www.362tq.com/tianjun/40tian.html 推荐查看天气:http://www.362tq.com/dachaidan/ 推荐查看天气:http://www.362tq.com/dachaidan/zuotian.html 推荐查看天气:http://www.362tq.com/dachaidan/7tian.html 推荐查看天气:http://www.362tq.com/dachaidan/10tian.html 推荐查看天气:http://www.362tq.com/dachaidan/15tian.html 推荐查看天气:http://www.362tq.com/dachaidan/40tian.html 推荐查看天气:http://www.362tq.com/linghu/

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码