--- title: 'react报错:Can‘t perform a React state update on an unmounted component' date: 2021-07-24 11:54:00 --- ![](https://img-blog.csdnimg.cn/20210724114413809.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h1dG9uZ2Jhbw,size_16,color_FFFFFF,t_70) ![](https://img-blog.csdnimg.cn/20210724114716186.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h1dG9uZ2Jhbw,size_16,color_FFFFFF,t_70) 解决方案: ```javascript //生成cancelToken,用于取消请求 const getCancelSource = () => { return axios.CancelToken.source() } //挂载时异步获取所属分类数据 useEffect(() => { const source = getCancelSource() Api.light.category(source.token).then((res) => { if (res.state === 1) { const category = formatCategory({ categoryOptions: res.data }) setCategoryOptions(category) console.log('category') } }).catch(err => { console.log(err) }) return () => { console.log('卸载') source.cancel() } }, []) ``` ![](https://img-blog.csdnimg.cn/20210724115130157.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h1dG9uZ2Jhbw,size_16,color_FFFFFF,t_70) ![](https://img-blog.csdnimg.cn/20210724115217490.png?x-oss-processimage/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h1dG9uZ2Jhbw,size_16,color_FFFFFF,t_70) 参考链接:[http://www.axios-js.com/zh-cn/docs/#%E5%8F%96%E6%B6%88](http://www.axios-js.com/zh-cn/docs/#%E5%8F%96%E6%B6%88) ```javascript const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // 处理错误 } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // 取消请求(message 参数是可选的) source.cancel('Operation canceled by the user.'); ``` axios config的一个字段: ```javascript // `cancelToken` 指定用于取消请求的 cancel token // (查看后面的 Cancellation 这节了解更多) cancelToken: new CancelToken(function (cancel) { }) ```