解决方案:
//生成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()
}
}, [])
参考链接:http://www.axios-js.com/zh-cn/docs/#%E5%8F%96%E6%B6%88
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的一个字段:
// `cancelToken` 指定用于取消请求的 cancel token
// (查看后面的 Cancellation 这节了解更多)
cancelToken: new CancelToken(function (cancel) {
})