使用Axios的'Cancel Token”机制可以解决这个问题。在发送Axios请求时,创建一个取消令牌并将其附加到请求中。如果请求被重复调用,则之前的请求将被取消并用新的请求替换。
以下是一个使用取消令牌的示例:
import axios from 'axios';
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/api/data', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
}).then(response => {
console.log(response);
}).catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle normal errors
}
});
// cancel the request (the message parameter is optional)
cancel('Operation canceled by the user.');
当发送新请求时,调用上一个请求的 'cancel” 函数即可取消上一个请求。
// cancel the previous request before sending a new one
if (typeof cancel === 'function') {
cancel('Operation canceled due to new request.');
}
axios.post('/api/data', { data }, {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
}).then(response => {
console.log(response);
}).catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle normal errors
}
});
这样,即使用户在请求发送前多次单击,也只会发送最后一次请求,并且之前的请求将被取消。