JavaScript 中 AbortController 的中断请求与事件监听清理实战
最近在排查一个后台管理系统里偶发的内存泄漏问题时,发现几个页面在快速切换菜单后,仍然有未完成的 fetch 请求在持续占用资源,甚至触发了 setState 警告。这类场景其实很常见:用户点击某个按钮发起数据请求,还没等响应回来就跳走了,或者连续触发了多个相同请求,旧请求返回后覆盖了新数据。以前我们习惯用 axios 的 CancelToken 或者自己维护一个 flag 来判断是否忽略结果,但这只是“忽略”,请求本身并没有被真正取消,浏览器的网络连接依然存在。AbortController 提供了一种更标准的取消机制,不仅能中断 fetch,还能移除事件监听器,甚至配合自定义异步任务使用。这篇内容会从实际代码出发,梳理 AbortController 的基本用法、在请求竞态和组件卸载时的处理方式,以及如何结合事件监听器避免重复绑定带来的泄漏。 先看一个最基础的例子。fetch 接受一个 signal 参数,这个 signal 来自 AbortController 实例。调用 controller.abort() 之后,进行中的 fetch 会直接 reject 一个 AbortError。 ```js const controller = new AbortController(); const { signal } = controller; fetch('/api/users', { signal }) .then(res => res.json()) .then(data => console.log(data)) .catch(err => { if (err.name === 'AbortError') { console.log('请求被取消'); } else { console.error('请求失败', err); } }); // 在需要取消的时候调用 controller.abort(); ``` 这里有个细节:abort() 之后 signal 会变成 aborted 状态,并且不会再恢复。如果同一个 controller 再次用于新的 fetch,会立刻抛出 AbortError。所以每次请求都应该创建新的 AbortController 实例。 实际项目中更常见的是搜索框联想功能。用户每输入一个字符就发一次请求,但只有最后一次输入的结果需要展示。如果不做取消,旧请求可能后返回,导致列表内容闪烁或者显示错误结果。 ```js let currentController = null; async function search(keyword) { if (currentController) { currentController.abort(); } currentController = new AbortController(); try { const res = await fetch(`/api/search?q=${encodeURIComponent(keyword)}`, { signal: currentController.signal }); const data = await res.json(); renderList(data); } catch (err) { if (err.name !== 'AbortError') { showError(err); } } finally { currentController = null; } } ``` 这里用 currentController 保存最近一次的控制器,新请求发起前先取消旧的。注意在 finally 里把 currentController 置空,避免在快速连续调用时错误地取消已经完成的请求。 在 React 或 Vue 组件里,经常遇到组件卸载后请求才返回,然后调用 setState 或者修改响应式数据,造成警告甚至内存泄漏。以前的做法是在组件里维护一个 isMounted 变量,但 AbortController 更彻底。以 React 函数组件为例: ```js 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(data => setUser(data)) .catch(err => { if (err.name !== 'AbortError') { console.error(err); } }); return () => { controller.abort(); }; }, [userId]); if (!user) return Loading...; return {user.name}; } ``` 当 userId 变化或者组件卸载时,useEffect 的清理函数会调用 abort(),请求被取消,后面的 then 不会执行,setUser 也不会被调用。这样就不需要手动维护 isMounted 标志了。 AbortController 的另一个实用场景是移除事件监听器。addEventListener 支持传入一个 signal,当 signal 被 abort 时,监听器会自动移除。这在需要动态绑定和解绑大量事件时特别省心。 ```js const controller = new AbortController(); const { signal } = controller; window.addEventListener('resize', handleResize, { signal }); window.addEventListener('scroll', handleScroll, { signal }); document.getElementById('btn').addEventListener('click', handleClick, { signal }); // 需要清理的时候 controller.abort(); ``` 如果不使用 signal,就必须记住每个监听器的引用以及对应的元素,分别调用 removeEventListener。现在一个 abort() 就能全部移除。在单页应用里,页面切换时清理全局事件监听特别有用。 有时候我们需要把 AbortController 和自定义的异步任务结合。比如封装一个支持取消的延时函数: ```js function delay(ms, signal) { return new Promise((resolve, reject) => { const timer = setTimeout(resolve, ms); if (signal) { if (signal.aborted) { clearTimeout(timer); reject(new DOMException('Aborted', 'AbortError')); return; } signal.addEventListener('abort', () => { clearTimeout(timer); reject(new DOMException('Aborted', 'AbortError')); }, { once: true }); } }); } ``` 这样调用方就可以用同一个 signal 统一取消多个异步操作。注意这里用了 DOMException 来模拟原生 AbortError 的行为,方便上层统一处理。 另一个容易踩坑的地方是,abort() 之后 signal 上的 abort 事件只会触发一次。如果需要在取消后执行清理逻辑,应该监听 abort 事件而不是在 catch 里做所有事情。 ```js const controller = new AbortController(); const { signal } = controller; signal.addEventListener('abort', () => { console.log('取消发生了,清理资源'); }, { once: true }); ``` 比如上传文件时,可以在 abort 事件里清理临时文件或者关闭 WebSocket 连接。 还有一点,AbortController 不能直接取消已经完成的请求,也不会影响已经 resolve 的 Promise。所以如果请求已经成功返回,再调用 abort() 不会有任何效果。这其实符合预期,不需要额外判断。 在 Node.js 环境中,从 v15 开始也支持 AbortController,可以用于中断 http 请求或者自定义流。比如使用 undici 或者 node-fetch 时,同样可以传入 signal。 ```js const { request } = require('undici'); const controller = new AbortController(); request('http://example.com', { signal: controller.signal }) .then(({ statusCode, body }) => { // 处理响应 }) .catch(err => { if (err.name === 'AbortError') { console.log('请求中止'); } }); setTimeout(() => controller.abort(), 1000); ``` 如果项目里还在用 axios,它从 v0.22.0 开始也支持 AbortController 作为 cancelToken 的替代方案。迁移时只需要把 CancelToken.source() 换成 new AbortController(),然后把 signal 传给请求配置即可。 ```js const controller = new AbortController(); axios.get('/api/data', { signal: controller.signal }).catch(err => { if (axios.isCancel(err)) { console.log('请求取消'); } }); controller.abort(); ``` axios 内部会把 AbortError 转换成自己的 Cancel 错误,用 axios.isCancel 判断更准确。 实际开发中,把 AbortController 和请求库结合时,注意不要在组件卸载后还去访问已经废弃的状态。虽然 abort 能阻止 then 执行,但如果代码里用了 async/await 并且没有正确处理异常,仍然可能走到后面的逻辑。最好在 catch 里判断错误类型,只处理非取消的错误。 最后提一下兼容性。AbortController 在现代浏览器中支持已经很好,Chrome 66+、Firefox 57+、Safari 12.1+ 都支持。如果还需要支持 IE,就只能用 polyfill 或者继续用旧的取消方案。不过现在大部分项目已经不需要考虑 IE 了。 推荐查看天气:http://www.362tq.com/heshuo/40tian.html 推荐查看天气:http://www.362tq.com/bohu/ 推荐查看天气:http://www.362tq.com/bohu/zuotian.html 推荐查看天气:http://www.362tq.com/bohu/7tian.html 推荐查看天气:http://www.362tq.com/bohu/10tian.html 推荐查看天气:http://www.362tq.com/bohu/15tian.html 推荐查看天气:http://www.362tq.com/bohu/40tian.html 推荐查看天气:http://www.362tq.com/akesu/ 推荐查看天气:http://www.362tq.com/akesu/zuotian.html 推荐查看天气:http://www.362tq.com/akesu/7tian.html 推荐查看天气:http://www.362tq.com/akesu/10tian.html 推荐查看天气:http://www.362tq.com/akesu/15tian.html 推荐查看天气:http://www.362tq.com/akesu/40tian.html 推荐查看天气:http://www.362tq.com/wensu/ 推荐查看天气:http://www.362tq.com/wensu/zuotian.html 推荐查看天气:http://www.362tq.com/wensu/7tian.html 推荐查看天气:http://www.362tq.com/wensu/10tian.html 推荐查看天气:http://www.362tq.com/wensu/15tian.html 推荐查看天气:http://www.362tq.com/wensu/40tian.html 推荐查看天气:http://www.362tq.com/kuche/ 推荐查看天气:http://www.362tq.com/kuche/zuotian.html 推荐查看天气:http://www.362tq.com/kuche/7tian.html 推荐查看天气:http://www.362tq.com/kuche/10tian.html 推荐查看天气:http://www.362tq.com/kuche/15tian.html 推荐查看天气:http://www.362tq.com/kuche/40tian.html 推荐查看天气:http://www.362tq.com/shaya/ 推荐查看天气:http://www.362tq.com/shaya/zuotian.html 推荐查看天气:http://www.362tq.com/shaya/7tian.html 推荐查看天气:http://www.362tq.com/shaya/10tian.html 推荐查看天气:http://www.362tq.com/shaya/15tian.html 推荐查看天气:http://www.362tq.com/shaya/40tian.html 推荐查看天气:http://www.362tq.com/xinhe/ 推荐查看天气:http://www.362tq.com/xinhe/zuotian.html 推荐查看天气:http://www.362tq.com/xinhe/7tian.html 推荐查看天气:http://www.362tq.com/xinhe/10tian.html 推荐查看天气:http://www.362tq.com/xinhe/15tian.html 推荐查看天气:http://www.362tq.com/xinhe/40tian.html 推荐查看天气:http://www.362tq.com/baichengxian/ 推荐查看天气:http://www.362tq.com/baichengxian/zuotian.html 推荐查看天气:http://www.362tq.com/baichengxian/7tian.html 推荐查看天气:http://www.362tq.com/baichengxian/10tian.html 推荐查看天气:http://www.362tq.com/baichengxian/15tian.html 推荐查看天气:http://www.362tq.com/baichengxian/40tian.html 推荐查看天气:http://www.362tq.com/wushi/ 推荐查看天气:http://www.362tq.com/wushi/zuotian.html 推荐查看天气:http://www.362tq.com/wushi/7tian.html 推荐查看天气:http://www.362tq.com/wushi/10tian.html 推荐查看天气:http://www.362tq.com/wushi/15tian.html 推荐查看天气:http://www.362tq.com/wushi/40tian.html 推荐查看天气:http://www.362tq.com/awati/ 推荐查看天气:http://www.362tq.com/awati/zuotian.html 推荐查看天气:http://www.362tq.com/awati/7tian.html 推荐查看天气:http://www.362tq.com/awati/10tian.html 推荐查看天气:http://www.362tq.com/awati/15tian.html 推荐查看天气:http://www.362tq.com/awati/40tian.html 推荐查看天气:http://www.362tq.com/keping/ 推荐查看天气:http://www.362tq.com/keping/zuotian.html 推荐查看天气:http://www.362tq.com/keping/7tian.html 推荐查看天气:http://www.362tq.com/keping/10tian.html 推荐查看天气:http://www.362tq.com/keping/15tian.html 推荐查看天气:http://www.362tq.com/keping/40tian.html 推荐查看天气:http://www.362tq.com/kezhou/ 推荐查看天气:http://www.362tq.com/kezhou/zuotian.html 推荐查看天气:http://www.362tq.com/kezhou/7tian.html 推荐查看天气:http://www.362tq.com/kezhou/10tian.html 推荐查看天气:http://www.362tq.com/kezhou/15tian.html 推荐查看天气:http://www.362tq.com/kezhou/40tian.html 推荐查看天气:http://www.362tq.com/atushi/ 推荐查看天气:http://www.362tq.com/atushi/zuotian.html 推荐查看天气:http://www.362tq.com/atushi/7tian.html 推荐查看天气:http://www.362tq.com/atushi/10tian.html 推荐查看天气:http://www.362tq.com/atushi/15tian.html 推荐查看天气:http://www.362tq.com/atushi/40tian.html 推荐查看天气:http://www.362tq.com/aketao/ 推荐查看天气:http://www.362tq.com/aketao/zuotian.html 推荐查看天气:http://www.362tq.com/aketao/7tian.html 推荐查看天气:http://www.362tq.com/aketao/10tian.html 推荐查看天气:http://www.362tq.com/aketao/15tian.html 推荐查看天气:http://www.362tq.com/aketao/40tian.html 推荐查看天气:http://www.362tq.com/aheqi/ 推荐查看天气:http://www.362tq.com/aheqi/zuotian.html 推荐查看天气:http://www.362tq.com/aheqi/7tian.html 推荐查看天气:http://www.362tq.com/aheqi/10tian.html 推荐查看天气:http://www.362tq.com/aheqi/15tian.html 推荐查看天气:http://www.362tq.com/aheqi/40tian.html 推荐查看天气:http://www.362tq.com/wuqia/ 推荐查看天气:http://www.362tq.com/wuqia/zuotian.html 推荐查看天气:http://www.362tq.com/wuqia/7tian.html 推荐查看天气:http://www.362tq.com/wuqia/10tian.html 推荐查看天气:http://www.362tq.com/wuqia/15tian.html 推荐查看天气:http://www.362tq.com/wuqia/40tian.html 推荐查看天气:http://www.362tq.com/kashi/ 推荐查看天气:http://www.362tq.com/kashi/zuotian.html 推荐查看天气:http://www.362tq.com/kashi/7tian.html 推荐查看天气:http://www.362tq.com/kashi/10tian.html 推荐查看天气:http://www.362tq.com/kashi/15tian.html 推荐查看天气:http://www.362tq.com/kashi/40tian.html 推荐查看天气:http://www.362tq.com/shufu/ 推荐查看天气:http://www.362tq.com/shufu/zuotian.html 推荐查看天气:http://www.362tq.com/shufu/7tian.html 推荐查看天气:http://www.362tq.com/shufu/10tian.html 推荐查看天气:http://www.362tq.com/shufu/15tian.html 推荐查看天气:http://www.362tq.com/shufu/40tian.html 推荐查看天气:http://www.362tq.com/shule/ 推荐查看天气:http://www.362tq.com/shule/zuotian.html 推荐查看天气:http://www.362tq.com/shule/7tian.html 推荐查看天气:http://www.362tq.com/shule/10tian.html 推荐查看天气:http://www.362tq.com/shule/15tian.html 推荐查看天气:http://www.362tq.com/shule/40tian.html 推荐查看天气:http://www.362tq.com/yingjisha/ 推荐查看天气:http://www.362tq.com/yingjisha/zuotian.html 推荐查看天气:http://www.362tq.com/yingjisha/7tian.html 推荐查看天气:http://www.362tq.com/yingjisha/10tian.html 推荐查看天气:http://www.362tq.com/yingjisha/15tian.html 推荐查看天气:http://www.362tq.com/yingjisha/40tian.html 推荐查看天气:http://www.362tq.com/zepu/ 推荐查看天气:http://www.362tq.com/zepu/zuotian.html 推荐查看天气:http://www.362tq.com/zepu/7tian.html 推荐查看天气:http://www.362tq.com/zepu/10tian.html 推荐查看天气:http://www.362tq.com/zepu/15tian.html 推荐查看天气:http://www.362tq.com/zepu/40tian.html 推荐查看天气:http://www.362tq.com/shache/ 推荐查看天气:http://www.362tq.com/shache/zuotian.html 推荐查看天气:http://www.362tq.com/shache/7tian.html 推荐查看天气:http://www.362tq.com/shache/10tian.html 推荐查看天气:http://www.362tq.com/shache/15tian.html 推荐查看天气:http://www.362tq.com/shache/40tian.html 推荐查看天气:http://www.362tq.com/yecheng/ 推荐查看天气:http://www.362tq.com/yecheng/zuotian.html 推荐查看天气:http://www.362tq.com/yecheng/7tian.html 推荐查看天气:http://www.362tq.com/yecheng/10tian.html 推荐查看天气:http://www.362tq.com/yecheng/15tian.html 推荐查看天气:http://www.362tq.com/yecheng/40tian.html 推荐查看天气:http://www.362tq.com/maigaiti/ 推荐查看天气:http://www.362tq.com/maigaiti/zuotian.html 推荐查看天气:http://www.362tq.com/maigaiti/7tian.html 推荐查看天气:http://www.362tq.com/maigaiti/10tian.html 推荐查看天气:http://www.362tq.com/maigaiti/15tian.html 推荐查看天气:http://www.362tq.com/maigaiti/40tian.html 推荐查看天气:http://www.362tq.com/yuepuhu/ 推荐查看天气:http://www.362tq.com/yuepuhu/zuotian.html 推荐查看天气:http://www.362tq.com/yuepuhu/7tian.html 推荐查看天气:http://www.362tq.com/yuepuhu/10tian.html 推荐查看天气:http://www.362tq.com/yuepuhu/15tian.html 推荐查看天气:http://www.362tq.com/yuepuhu/40tian.html 推荐查看天气:http://www.362tq.com/jiashi/ 推荐查看天气:http://www.362tq.com/jiashi/zuotian.html 推荐查看天气:http://www.362tq.com/jiashi/7tian.html 推荐查看天气:http://www.362tq.com/jiashi/10tian.html 推荐查看天气:http://www.362tq.com/jiashi/15tian.html 推荐查看天气:http://www.362tq.com/jiashi/40tian.html 推荐查看天气:http://www.362tq.com/bachu/ 推荐查看天气:http://www.362tq.com/bachu/zuotian.html 推荐查看天气:http://www.362tq.com/bachu/7tian.html 推荐查看天气:http://www.362tq.com/bachu/10tian.html 推荐查看天气:http://www.362tq.com/bachu/15tian.html 推荐查看天气:http://www.362tq.com/bachu/40tian.html 推荐查看天气:http://www.362tq.com/tashikuergan/ 推荐查看天气:http://www.362tq.com/tashikuergan/zuotian.html 推荐查看天气:http://www.362tq.com/tashikuergan/7tian.html 推荐查看天气:http://www.362tq.com/tashikuergan/10tian.html 推荐查看天气:http://www.362tq.com/tashikuergan/15tian.html 推荐查看天气:http://www.362tq.com/tashikuergan/40tian.html 推荐查看天气:http://www.362tq.com/hetian/ 推荐查看天气:http://www.362tq.com/hetian/zuotian.html 推荐查看天气:http://www.362tq.com/hetian/7tian.html 推荐查看天气:http://www.362tq.com/hetian/10tian.html 推荐查看天气:http://www.362tq.com/hetian/15tian.html 推荐查看天气:http://www.362tq.com/hetian/40tian.html 推荐查看天气:http://www.362tq.com/moyu/ 推荐查看天气:http://www.362tq.com/moyu/zuotian.html 推荐查看天气:http://www.362tq.com/moyu/7tian.html 推荐查看天气:http://www.362tq.com/moyu/10tian.html 推荐查看天气:http://www.362tq.com/moyu/15tian.html 推荐查看天气:http://www.362tq.com/moyu/40tian.html 推荐查看天气:http://www.362tq.com/pishan/ 推荐查看天气:http://www.362tq.com/pishan/zuotian.html 推荐查看天气:http://www.362tq.com/pishan/7tian.html 推荐查看天气:http://www.362tq.com/pishan/10tian.html 推荐查看天气:http://www.362tq.com/pishan/15tian.html 推荐查看天气:http://www.362tq.com/pishan/40tian.html 推荐查看天气:http://www.362tq.com/luopu/ 推荐查看天气:http://www.362tq.com/luopu/zuotian.html 推荐查看天气:http://www.362tq.com/luopu/7tian.html 推荐查看天气:http://www.362tq.com/luopu/10tian.html 推荐查看天气:http://www.362tq.com/luopu/15tian.html 推荐查看天气:http://www.362tq.com/luopu/40tian.html 推荐查看天气:http://www.362tq.com/cele/ 推荐查看天气:http://www.362tq.com/cele/zuotian.html 推荐查看天气:http://www.362tq.com/cele/7tian.html 推荐查看天气:http://www.362tq.com/cele/10tian.html 推荐查看天气:http://www.362tq.com/cele/15tian.html 推荐查看天气:http://www.362tq.com/cele/40tian.html 推荐查看天气:http://www.362tq.com/yutian/ 推荐查看天气:http://www.362tq.com/yutian/zuotian.html 推荐查看天气:http://www.362tq.com/yutian/7tian.html 推荐查看天气:http://www.362tq.com/yutian/10tian.html 推荐查看天气:http://www.362tq.com/yutian/15tian.html 推荐查看天气:http://www.362tq.com/yutian/40tian.html 推荐查看天气:http://www.362tq.com/minfeng/