Axios request is not cancelled when a React component unmounts
The request still finishes and updates state after the component is gone or the id changedShort answer
Axios cancels a request when you pass it an AbortSignal and later call abort() on its controller. In React, create the controller inside the effect and abort it in the cleanup function. The old CancelToken way is deprecated. A cancelled call rejects, so check axios.isCancel in the catch block.
Fix it fast
1Find out which cause you have
Open the Network tab, trigger the effect, then navigate away. A request that shows as cancelled means the abort works; one that completes means the cleanup never calls abort() on the same controller the request received.
useEffect(() => { console.log('effect setup'); return () => console.log('effect cleanup'); }, [id]);2Match what you see, then jump to its fix
- 1
The cleanup runs (you see the log) but the request completes anywayThe signal was never passed to axios, or the controller is created outside the effectFix - 2
The source contains axios.CancelToken.source() or cancelToken in the request configThe code still uses the deprecated CancelToken APIFix - 3
A cancel is logged or shown as an error; the error code is ERR_CANCELED and its name is CanceledErrorThe cancelled request lands in catch and is handled as a failureFix - 4
Two identical requests on mount, the first one cancelled, only in developmentStrict Mode runs the effect twice in developmentFix
- 1
What does the error look like?
The request still finishes and updates state after the component is gone or the id changedA cancelled request is logged as an error in the catch blockIn development the request fires twice
Cause 1 of 4
The signal was never passed to axios, or the controller is created outside the effect
1Check
Axios only cancels the request that received the signal option. The cleanup must call abort() on that same controller, so create it inside the effect where both the request and the cleanup can see it.
grep -rn "new AbortController" src2Fix
Create the controller inside the effect, pass its signal in the request config, and call abort() in the cleanup.
useEffect(() => {
const controller = new AbortController();
axios
.get(`/api/items/${id}`, { signal: controller.signal })
.then((res) => setItem(res.data));
return () => controller.abort();
}, [id]);3Verify
Change the id or unmount the component. The earlier request shows as cancelled in the Network tab.
console.log(controller.signal.aborted); // true after cleanupConfirmed by axios.rest
Cause 2 of 4
The code still uses the deprecated CancelToken API
1Check
The Axios documentation says the CancelToken API is deprecated and will be removed in the next major release, and recommends AbortController.
grep -rn "CancelToken" src2Fix
Replace the token with an AbortController and the signal option, as in the first cause.
// before
const source = axios.CancelToken.source();
axios.get(url, { cancelToken: source.token });
return () => source.cancel();
// after
const controller = new AbortController();
axios.get(url, { signal: controller.signal });
return () => controller.abort();3Verify
Search again: no CancelToken left, and the request still cancels on cleanup.
grep -rn "CancelToken" srcConfirmed by axios.rest
Cause 3 of 4
The cancelled request lands in catch and is handled as a failure
1Check
The Axios error documentation lists ERR_CANCELED as the code for a request cancelled explicitly through an AbortSignal, and recommends axios.isCancel(error) to detect it.
.catch((error) => console.log(error.name, error.code, axios.isCancel(error)));2Fix
Ignore the cancellation in catch and handle only real failures.
axios
.get(url, { signal: controller.signal })
.then((res) => setData(res.data))
.catch((error) => {
if (axios.isCancel(error)) return;
setError(error);
});3Verify
Navigate away mid-request. No error state is set and nothing is logged as a failure.
console.log(axios.isCancel(error));Confirmed by axios.rest
Cause 4 of 4
Strict Mode runs the effect twice in development
1Check
React documents that in Strict Mode it runs one extra setup and cleanup cycle before the first real setup, to check that your cleanup mirrors your setup.
grep -rn "StrictMode" src2Fix
Do not remove Strict Mode. A correct cleanup that aborts the request makes the extra cycle harmless: the first request is cancelled and the second one is used.
useEffect(() => {
const controller = new AbortController();
load(controller.signal);
return () => controller.abort();
}, []);3Verify
In production the request is sent once. In development the first is cancelled and the second completes.
npm run build && npm run previewConfirmed by react.dev
How do I stop it coming back?
- Always create the AbortController inside the effect that starts the request.
- Treat axios.isCancel(error) as a normal outcome in every catch block.
- Replace CancelToken before upgrading to the next major version of axios.
- For data fetching used in many places, consider a library such as TanStack Query, which React's own documentation also suggests.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- TaskvareA task and project-management suite: React on the web, Flutter on mobile, TypeScript underneath.
Related fixes
Web apps
AxiosError Network Error with code ERR_NETWORK in a React app
Network Error
ERR_NETWORK means the request produced no readable response.
4 causes, each with a fixWeb apps
Module not found for antd/dist/antd.less after upgrading to Ant Design 5
Module not found: Error: Can't resolve 'antd/dist/antd.less'
Ant Design 5 dropped Less and the bundled CSS file for CSS-in-JS, so antd/dist/antd.less no longer exists.
3 causes, each with a fixWeb apps
Astro Code component fails inside a React component
Astro components cannot be rendered directly via function call
Astro components such as Code only exist on the server and render static HTML.
2 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
How to catch and handle a 422 from Axios in a Redux thunk
action.error.message is 'Rejected' and action.payload is undefined
A 422 means the server read the request but cannot process its content, so repeating it unchanged fails again.
4 causes, each with a fixWeb apps
axios gets 429 Too Many Requests from a React app
429 (Too Many Requests)
A 429 comes from the server or an API gateway, not from axios: your client sent too many requests in a window.
4 causes, each with a fix