Understanding Axios CancelToken Mechanism and Solving Data Mixing When Rapidly Switching Vue H5 Routes
This article analyzes a bug where rapid route switching in a Vue H5 project caused data from different routes to mix, explains how Axios CancelToken works, shows the implementation of request cancellation via interceptors, and discusses deeper insights and further possibilities for frontend developers.
When developing a Vue‑based H5 project, a bug was discovered: fast switching between routes caused the requests of different routes to share the same interface, leading to mixed data when the network is slow.
Problem description
After setting the network to mid‑tier mobile , quickly changing routes resulted in the data of the second route ("Pending client signature") being accumulated with the data of the first route ("Draft agreement").
Solution effect
Adding a request‑cancellation step on route change made the data behave correctly.
Implementation details
In the entry file a CancelToken is created via Axios:
const { CancelToken, isCancel } = axios;
const source = CancelToken.source();The request interceptor adds the token to each request configuration:
axios.interceptors.request.use(config => {
config.cancelToken = source.token;
return config;
});Principle analysis – Axios basics
Axios natively supports request cancellation. Two ways are provided:
// 1. Using CancelToken
const { CancelToken } = axios;
const source = CancelToken.source();
axios.get('/user/12345', { cancelToken: source.token })
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
}
});
// 2. Using an executor function
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) { cancel = c; })
});
// later
cancel();Axios request flow
The request goes through an interceptor chain before reaching dispatchRequest . The chain is built as:
Promise.resolve(config)
.then(interceptor.request.fulfilled, interceptor.request.rejected)
.then(dispatchRequest, undefined)
.then(interceptor.response.fulfilled, interceptor.response.rejected);Inside dispatchRequest the adapter (XHR in browsers) is called, which returns another promise.
XHR adapter source
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
// ... create XMLHttpRequest instance named request
if (config.cancelToken) {
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) return;
request.abort();
reject(cancel);
request = null;
});
}
// ... send request
});
};When the cancelToken.promise resolves, the XHR request is aborted and the promise chain is rejected.
CancelToken implementation
function CancelToken(executor) {
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) return;
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
CancelToken.source = function () {
var cancel;
var token = new CancelToken(function executor(c) { cancel = c; });
return { token: token, cancel: cancel };
};Calling the cancel function resolves the internal promise, which triggers the abort logic in the XHR adapter.
Reflection
By sharing a single CancelToken across requests of the same route, cancelling it cancels all pending requests, preventing data mixing during rapid navigation.
Further ideas include using the same cancellation pattern for fetch or designing custom wrappers for other HTTP libraries.
References
https://github.com/axios/axios
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest
Beike Product & Technology
As Beike's official product and technology account, we are committed to building a platform for sharing Beike's product and technology insights, targeting internet/O2O developers and product professionals. We share high-quality original articles, tech salon events, and recruitment information weekly. Welcome to follow us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.