常规的axios取消请求方式:
v0.22.0及之后版本
const controller = new AbortController();
axios.get('/user/12345', {
signal: controller.signal
}).then(function(response) {
//处理错误
});
// 取消请求
controller.abort()
v0.22.0之前版本
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
// 处理错误
});
// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');
针对post请求并且设置了onUploadProgress的情况,上述代码不起作用,需要用useState
const [controller, setController] = useState(new AbortController());
axios.get('/user/12345', {
signal: controller.signal
}).then(function(response) {
//处理错误
});
// 取消请求
controller.abort()
//解决下次不能发请求问题
setController(new AbortController())
网友评论