Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

Axios request is not cancelled when a React component unmounts

ErrorThe request still finishes and updates state after the component is gone or the id changed

Short 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.

  • Applies to React 19, axios 1.x
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 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]);
  2. 2Match what you see, then jump to its fix

    1. 1The 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. 2The source contains axios.CancelToken.source() or cancelToken in the request configThe code still uses the deprecated CancelToken APIFix
    3. 3A 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. 4Two identical requests on mount, the first one cancelled, only in developmentStrict Mode runs the effect twice in developmentFix

What does the error look like?

  • The request still finishes and updates state after the component is gone or the id changed
  • A cancelled request is logged as an error in the catch block
  • In 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" src

2Fix

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 cleanup

Confirmed by axios.rest

Did this fix it?

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" src

2Fix

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" src

Confirmed by axios.rest

Did this fix it?

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

Did this fix it?

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" src

2Fix

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 preview

Confirmed by react.dev

Did this fix it?

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:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.