React组件卸载时如何取消指定Axios请求
实现组件卸载时取消特定Axios请求的方案
核心实现逻辑
从Axios 0.22版本开始,官方原生支持浏览器标准的AbortController接口实现请求中断,完全兼容React组件生命周期逻辑,不需要改动原有transport层的通用发送逻辑,仅需两步配置即可完成需求。
第一步:调整API封装,支持透传取消信号
修改原有productAPI的getProducts方法,新增配置入参,把从组件传入的取消信号挂载到Axios请求配置上:
import * as axios from "axios"; export const productAPI = { // 接收外部传入的Axios配置项 getProducts(config = {}) { return axios({ method: 'get', url: `/api/products`, // 透传外部传入的取消信号 signal: config.signal }); } };
第二步:在组件逻辑中接入中断逻辑
利用useEffect的清理函数(组件卸载时自动执行)触发请求中断,同时做好异常拦截,避免取消请求触发无意义的错误弹窗和状态更新警告:
useEffect(() => { // 初始化AbortController实例,用于生成取消信号、触发中断 const abortController = new AbortController(); // 标记组件是否已卸载,避免卸载后触发setState let isComponentUnmounted = false; setLoading(true); productAPI.getProducts({ signal: abortController.signal }) .then((response) => { // 组件已卸载时不执行后续业务逻辑 if (isComponentUnmounted) return; if(response.status === 200) { history.push(`${pathWithLocation}${PAGES.newLoan}`); } }) .catch((error) => { if (isComponentUnmounted) return; // 判断错误是否由主动取消请求触发,是的话直接跳过后续错误处理 if (axios.isCancel(error)) { return; } // 原有业务错误处理逻辑 if (error.response.data.error.message) { dispatch(addModal({ type: 'basic', size: 'middle', title: 'some title', text: error.response.data.error.message, buttons: [{ buttonLabel: 'ОК', onClick: () => dispatch(removeModal()) }] })) } }) .finally(() => { // 组件未卸载时再更新loading状态,避免React抛出内存泄漏警告 if (!isComponentUnmounted) { setLoading(false); } }); // 组件卸载时的清理逻辑 return () => { isComponentUnmounted = true; // 主动中断在途的getProducts请求 abortController.abort(); } }, [])
旧版本Axios兼容方案
如果项目使用的Axios版本低于0.22,暂时无法升级,可以使用已被官方标记废弃的CancelToken接口实现同等能力:
- 调整API封装,接收cancelToken参数:
export const productAPI = { getProducts(cancelToken) { return axios({ method: 'get', url: `/api/products`, cancelToken }); } } - 组件逻辑中替换取消逻辑:
useEffect(() => { const cancelTokenSource = axios.CancelToken.source(); setLoading(true); productAPI.getProducts(cancelTokenSource.token) // 后续then/catch/finally逻辑和上述方案一致 .catch((error) => { if (axios.isCancel(error)) return; // 原有错误处理 }) return () => { // 组件卸载时取消请求 cancelTokenSource.cancel('组件卸载,中断当前请求'); } }, [])
内容的提问来源于stack exchange,提问作者howard wolowitz
相关产品推荐
相关产品推荐

