According to the docs axios supports the AbortController of the fetch API.

Cancellation

Axios supports AbortController to abort requests in fetch API way:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

It's not clear exactly where testController is declared:

let testController: AbortController;

but I suspect it's in the body of the function component and redeclared on a subsequent render cycle.

I suggest using a React ref to store an AbortController, and reference this ref value around your app. This is so the component holds on to a stable reference of the controller from render cycle to render cycle, to be referenced in any useEffect hook cleanup function to cancel in-flight requests if/when the component unmounts.

const abortControllerRef = useRef<AbortController>(new AbortController());

function loadTest() {
  TestAPI.getTest(abortControllerRef.current.signal)
    .then((e) => {
      console.log(e.data);
    })
    .catch((e) => {
      console.error(e);
    });
}

useEffect(() => {
  const controller = abortControllerRef.current;
  return () => {
    controller.abort();
  };
}, []);
Answer from Drew Reese on Stack Overflow
🌐
Axios
axios-http.com › docs › cancellation
Cancellation | Axios Docs
const controller = new AbortController(); const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token, signal: controller.signal }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', ...
Top answer
1 of 7
32

According to the docs axios supports the AbortController of the fetch API.

Cancellation

Axios supports AbortController to abort requests in fetch API way:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

It's not clear exactly where testController is declared:

let testController: AbortController;

but I suspect it's in the body of the function component and redeclared on a subsequent render cycle.

I suggest using a React ref to store an AbortController, and reference this ref value around your app. This is so the component holds on to a stable reference of the controller from render cycle to render cycle, to be referenced in any useEffect hook cleanup function to cancel in-flight requests if/when the component unmounts.

const abortControllerRef = useRef<AbortController>(new AbortController());

function loadTest() {
  TestAPI.getTest(abortControllerRef.current.signal)
    .then((e) => {
      console.log(e.data);
    })
    .catch((e) => {
      console.error(e);
    });
}

useEffect(() => {
  const controller = abortControllerRef.current;
  return () => {
    controller.abort();
  };
}, []);
2 of 7
8

I would recommend to read this post.

In a nutshell you would like to use useEffect to create controller, and, what is more important, to use return statement to abort the controller.

useEffect(() => {
 const controller = new AbortController();
 const signal = controller.signal;
 getData(signal)

 //cleanup function
 return () => {controller.abort();};
}, [fetchClick]);

getData function can then be your axios call in the form:

const getData = async (signal) =>{
 const res = await axios.get(url, {signal: signal}).then(...)
}
Discussions

reactjs - how to cancel/abort ajax request in axios - Stack Overflow
Good that is uses AbortController, but this answer isn't using Axios... More on stackoverflow.com
🌐 stackoverflow.com
AbortController Signal not cancelling requests with CORS
Describe the bug I am adding an AbortController signal to axios GET requests. With a simple GET request without modified headers, the backend GET endpoint was able to receive the cancel request. Ho... More on github.com
🌐 github.com
2
October 13, 2022
Trying to understand how timeout works for https.request

Hey there,

If what you mean by "timeout for this request" is that if the response is not received within 1 second, the request should be aborted. Then you need to use the AbortController.

What you do is to create a new abort controller

const controller = new AbortController();

The controller has a signal property you need to provide to the request (axios/fetch). It also has an abort function which will abort the request.

So first create a timeout in 1 sec. which will call the abort function

const timeoutId =  setTimeout(() => {
    controller.abort();
}, 1000);

Now in one second the controller will call the abort function. But, no one is listening yet. So let's add it to the request. I don't use axios but I would assume it is just an option just like when using the built in fetch function.

So now you should provide the signal to the request:

axios.get(url, { signal: controller.signal);

If the request goes well, clear the timeout.

clearTimeout(timeoutId);

Everything together looks like this:

// create abort the controller
const controller = new AbortController();

// abort request in 1 sec.
setTimeout(() => {
    controller.abort();
}, 1000);

try {
    const response = await axios.get(url, { signal: controller.signal);

    clearTimeout(timeoutId);

    // prints true if response status is 200 or 301. False otherwise
    console.log(String(response.ok));
} catch(err) {
    // handle network error
}

Using await requires the function you write to be async, but you'll understand this soon enough.

I hope this helps. But feel free to ask further questions.

Welcome to nodejs 👍

More on reddit.com
🌐 r/node
5
10
August 25, 2023
AbortController usage
It depends as always. But if you have some expensive calls to your server the AbortController can really help to minimize server load. Why should you let an stale request run? Also what if your request would update state with stale data because your user is clicking through some filter options or something? I would say AbortController is perfect for this type of scenarios. More on reddit.com
🌐 r/reactjs
5
3
October 2, 2022
🌐
Medium
medium.com › @rakeshraj2097 › efficient-request-handling-in-react-with-axios-and-abortcontroller-e47bafab87c9
Efficient Request Handling in React with Axios and AbortController | by Rakeshraj | Medium
June 12, 2024 - For example: A user navigates away from a page before a request completes. A new request is made that renders the previous one obsolete. To avoid race conditions in search functionalities.
🌐
Medium
03balogun.medium.com › practical-use-case-of-the-abortcontroller-and-axios-cancel-token-7c75bf85f3ea
Practical use case of the Abortcontroller and Axios cancel token | by Balogun Wahab | Medium
September 1, 2021 - When the fetch API request is initiated we pass the AbortSignal as an option inside the requests options object, this associates the signal and controller with the fetch request and allows us to abort it by calling AbortController.abort(). It is important to note that when the abort() method is called the fetch() promise rejects with a DOMException named AbortError. We can use the DOMException name to know if an error occurred due to request cancellation. Let us proceed with the implementation, with each line commented to explain what they do. To cancel an ongoing request using axios the cancel(…) method from the cancel token API which takes an optional parameter for a message is invoked.
🌐
DEV Community
dev.to › dharamgfx › mastering-request-cancellation-in-javascript-using-abortcontroller-with-axios-and-fetch-api-2589
Mastering Request Cancellation ❌ in JavaScript: Using AbortController with Axios and Fetch API.🚀💪 - DEV Community
June 24, 2024 - Create New Controller: A new AbortController instance is created, and its signal is used in the new request. Make Request: The request is made using the Fetch API, passing the signal.
🌐
GitHub
gist.github.com › adeelibr › d8f3f8859e2929f3f1adb80992f1dc09
Abort Controllers In Axios · GitHub
November 19, 2022 - I mean, the axios call in an action creator, but still the cancellation from the component · Copy link · Author · Can be done, the principals are the same for AbortController · Copy link · Since https://github.com/axios/axios#cancellation cancel token API proposal was withdrawn will this still work ?
🌐
GitHub
github.com › axios › axios › pull › 7266
Add Axios AbortController example HTML file by Arun24-8 · Pull Request #7266 · axios/axios
November 26, 2025 - It includes: Single Request Cancellation - Shows how to cancel a single ongoing request using AbortController · Multiple Concurrent Requests - Demonstrates canceling multiple requests at once with a shared AbortController · Navigation Simulation ...
Author   axios
Find elsewhere
🌐
Medium
medium.datadriveninvestor.com › aborting-cancelling-requests-with-fetch-or-axios-db2e93825a36
Aborting/Cancelling requests with Fetch or Axios | by Abhimanyu Chauhan | DataDrivenInvestor
January 4, 2024 - useEffect(() => { const controller = new AbortController(); const signal = controller.signal; setFetchRes("fetch request created"); hitApi(signal).then((res) => { setFetchRes(res); }); //cleanup function return () => {controller.abort();}; }, ...
🌐
Dillion's Blog
dillionmegida.com › p › abort-api-request-in-javascript
How to abort API requests in JavaScript - Dillion's Blog
const controller = new AbortController() const abortSignal = controller.signal function abortRequest() { controller.abort() } axios.get("api", { signal: abortSignal, })
🌐
OpenReplay
blog.openreplay.com › how-to-cancel-requests-in-axios
How To Cancel Requests in Axios
April 18, 2023 - Specifically, AbortController contains an AbortSignal object instance in the read-only signal property. This allows you to communicate with a DOM or HTTP request and abort it when the abort() method is called.
🌐
GitHub
gist.github.com › adeelibr › d4d7cc9c1903d77437aef61a1d94ff12
Abort Controller Axios Seperated Files Example · GitHub
Abort Controller Axios Seperated Files Example · Raw · Abort Controller version 2 · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
The New Stack
thenewstack.io › home › cancel asynchronous react app requests with abortcontroller
Cancel Asynchronous React App Requests with AbortController - The New Stack
April 24, 2024 - The following code imports Axios, which enables making the API request to the random user generator API. It also includes an onClick event listener that calls the getPicture function. This function requests the endpoint and sets the image generated to the pictureUrl state. The following code creates a ref for the abortController and initializes it with an empty string.
🌐
Medium
medium.com › gits-apps-insight › front-end-simple-request-cancellation-e4b534762559
Front-End — Simple Request Cancellation | by Huda Prasetyo | GITS Apps Insight | Medium
August 24, 2023 - For Axios below v0.22.0, you can’t use AbortController. Here we are going to implement axios cancellation when fetching API or when some users leave the page using Cancel Token. I’m going explain to the point and just share the example code of the hook, because the usage of this hook, is ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › AbortController
AbortController - Web APIs - MDN Web Docs
September 17, 2025 - Creates a new AbortController object instance. ... Returns an AbortSignal object instance, which can be used to communicate with, or to abort, an asynchronous operation. ... Aborts an asynchronous operation before it has completed. This is able to abort fetch requests, consumption of any response ...
🌐
GitHub
github.com › axios › axios › issues › 5121
AbortController Signal not cancelling requests with CORS · Issue #5121 · axios/axios
October 13, 2022 - // import import axios from 'axios' ... and cancel it let abortController = new AbortController() axios.get("someurl", { signal: abortController.signal }) setTimeout(() => { abortController.abort() }, 5000)...
Author   patrickluk
🌐
Medium
medium.com › @rado.sabo › abortcontroller-abort-ongoing-calls-in-vue-with-axios-interceptor-584c9f0566a6
AbortController — Abort ongoing calls in Vue with Axios interceptor | by Rado | Medium
January 28, 2024 - In such a scenario, you can leverage Axios Interceptors. By using Axios Interceptor, you can intercept requests or responses before they are handled by the then or catch methods. A real-life example would be filtering or sorting data.
🌐
Plain English
plainenglish.io › blog › how-to-cancel-fetch-and-axios-requests-in-react-useeffect-hook
How to Cancel Fetch and Axios Requests in React’s useEffect Hook
October 20, 2023 - Let’s explore an example that includes a cleanup function capable of cancelling network requests for both Fetch and Axios clients. Here is how we can improve the code above. With the Fetch API, you can use the AbortController to cancel the request when the component unmounts.
🌐
GitHub
github.com › statelyai › xstate › discussions › 4691
Cancelling an axios request from within machine · statelyai/xstate · Discussion #4691
const documentUploadMachine = createMachine({ id: 'Document Upload Machine', context: ({ input: { file } }) => ({ file, uploadAbortController: new AbortController(), }), initial: 'init', on: { CANCEL: { target: '.cancelling' } }, states: { ... ...
Author   statelyai