Axios does not support canceling requests at the moment. Please see this issue for details.

UPDATE: Cancellation support was added in axios v0.15.

EDIT: The axios cancel token API is based on the withdrawn cancelable promises proposal.

UPDATE 2022: Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:

Example:

const controller = new AbortController();

axios.get('/foo/bar', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()
Answer from Nick Uraltsev on Stack Overflow
🌐
Axios
axios-http.com › docs › cancellation
Cancellation | Axios Docs
function newAbortSignal(timeoutMs) ... //Aborts request after 5 seconds }).then(function(response) { //... }); You can also cancel a request using a CancelToken....
Discussions

Cancel Request if a subsequent request is made?
I am trying to use Axios to implement a search function on my website. The issue I'm having is due to race conditions. When the user searches for "*" it returns all the results in the search index, which is large and takes a few seconds to return a response. If the user searches for "aeroplane", the search is much quicker than returning all the items in the index. The issue is that if you make the first request ... More on github.com
🌐 github.com
15
February 13, 2018
ajax - abort all Axios requests when change route use vue-router - Stack Overflow
how can i abort / cancel Axios request before complete when i change route use vue-router. when user open page it automatically send axios request to get some data, but user don't waiting to get More on stackoverflow.com
🌐 stackoverflow.com
How to cancel all prior requests and only display results from the latest API call.
You want to look up the Abort Controller API . It will let you cancel fetch requests that are in flight. What you can do is keep a reference to the controller while you are waiting for a response. If a new request is made you use the controller to cancel the old one. More on reddit.com
🌐 r/reactjs
71
55
June 28, 2021
Is it possible to cancel axios requests?
I'm building something similar to search lookahead, and with each change event to a text input I want to fire off a new set of axios get requests. When the change event occurs, I need to cancel all uncompleted axios requests from the las... More on github.com
🌐 github.com
12
July 23, 2015
🌐
npm
npmjs.com › package › axios-cancel
axios-cancel - npm
December 17, 2016 - console.log('request 2 cancelled'); } else { console.log('some other reason'); } }); axios.cancelAll(); // aborts all HTTP request, and cancels all promises · // logs `request 1 cancelled` // logs `request 2 cancelled` axiosCancel(instance: ...
      » npm install axios-cancel
    
Published   Dec 17, 2016
Version   0.2.2
Author   Thaer Abbas
🌐
Mastering JS
masteringjs.io › tutorials › axios › cancel
Axios Cancel Request - Mastering JS
November 23, 2020 - That's because there's no way to cancel an HTTP request in general once the request has already been sent over the network. If Axios has already sent the request, all cancel does is cause your Axios request to error out and ignore any response ...
🌐
OpenReplay
blog.openreplay.com › how-to-cancel-requests-in-axios
How To Cancel Requests in Axios
April 18, 2023 - Then, its signal property is passed to the Axios signal config in a cancellable HTTP GET request. When calling the abort() method on the controller, all pending HTTP requests involving that signal will be canceled.
🌐
Medium
julietonyekaoha.medium.com › react-cancel-all-axios-request-in-componentwillunmount-e5b2c978c071
Cancel all axios requests in React’s componentWillUnmount Lifecycle. | by Juliet Onyekaoha | Medium
May 11, 2022 - This means that if we have more than one API request in our component(regardless of the method, POST, GET, DELETE e.t.c), we can use one source variable to cancel all the requests.
🌐
GitHub
github.com › axios › axios › issues › 1361
Cancel Request if a subsequent request is made? · Issue #1361 · axios/axios
February 13, 2018 - The way I can think about how to do this is to issue a cancel token for every request, and before a request is made, the system will try to cancel any previous requests. The issue I'm having is when I try to use the cancel token, it cancels ...
Author   ChadTaljaardt
Find elsewhere
🌐
Medium
medium.com › @usman_qb › cancel-all-axios-requests-on-page-change-in-spa-eb8adfef79a9
Cancel all axios requests on page change in SPA | by Usman N. | Medium
May 11, 2022 - From axios official document, we know that AbortController is used to cancel requests but to make it happen in above scenario, I couldn’t find a single helpful material on Google. I could not find any simple way to make it work so I am going to explain the only way that worked for me.
Top answer
1 of 3
22

Update: Axios (0.22.0+)

CancelToken is now deprecated. Check @m0r answer for updated solution using AbortController. Here is the link from the official documentation:

https://axios-http.com/docs/cancellation

Original answer

Basically you have to generate a global cancel token

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

and use it in all your requests by passing it in the config parameter

GET request:

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

POST request:

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

Then, within a vue-router beforeEach navigation guard you can cancel all requests using:

source.cancel('Operation canceled by the user.');

Here's the official axios guide for cancellation: https://github.com/axios/axios#cancellation

2 of 3
10

Answer from @fabruex is correct. I just wanted to add here that if you have lot of api calls then you have to pass cancellation token in each api call config. In order to reduce that code, you can create axios instance and add request interceptor which will add that common cancellation token and then you can assign a new value to token when cancellation is done or your route has changed.

// Some global common cancel token source

let cancelSource = axios.CancelToken.source();

// Request interceptor

export const requestInterceptor = config => {
  config.cancelToken = cancelSource.token;
  return config;
};

// Add request interceptor like this
const request = axios.create({ baseURL: SOME_URL });
request.interceptors.request.use(requestInterceptor);


// Now you can use this axios instance like this

await request.get('/users');

// and

await request.post('/users', data);

// When you will cancel
cancelSource.cancel('Your cancellation message');

// And all the api calls initiated by axios instance which has request interceptor will be cancelled.

Edit to answer @Suneet Jain

You can create a class and create an instance which you can update

class CancelToken {
  constructor(initialValue) {
    this.source = initialValue;
  }
  getSource() {
    return this.source;
  }
  setSource(value) {
    this.source = value;
  }
  cancel() {
    this.source.cancel();
  }
}
export const cancelSource = new CancelToken(axios.CancelToken.source());

You can import that instance cancelSource and call cancel when required e.g. when you logout, you can call to cancel all request which have cancellation token given by cancelSource.getSource()

So after logout

cancelSource.cancel('CANCELLED');

And when again user will login, set new cancellation token to this global instance

cancelSource.setSource(axios.CancelToken.source());

🌐
Apidog
apidog.com › blog › axios-cancel-requests
How to cancel API requests with Axios
February 9, 2026 - That's where axios cancel requests come into play! So, how does this canceling thing work? Well, the key lies in the CancelToken provided by Axios. This token allows you to create a "cancelable operation" and associate ...
🌐
CodingDeft
codingdeft.com › posts › axios-cancel-previous-request-react
Cancelling previous requests in Search bar using Axios in React | CodingDeft.com
This can be done by storing a reference to the Axios call in a variable and canceling whenever a new request is triggered. ... For our demonstration let's set up a json-server Install the json-server globally.
🌐
Hmos
hmos.dev › en › how-to-cancel-at-axios
How to cancel at axios | hmos.dev
September 17, 2021 - A1. axios receives cancelToken ... cancelToken. If cancelToken is resolved from another axios request, All axios requests injected with the same cancelToken are terminated with reject because promise is resolved....
🌐
DEV Community
dev.to › nileshcodehub › how-to-cancel-api-calls-in-react-with-axios-a-step-by-step-guide-41b6
How to Cancel API Calls in React with Axios: A Step-by-Step Guide - DEV Community
March 7, 2025 - To cancel ongoing requests, we’ll use Axios’s CancelToken. This lets us stop a request if it’s not needed anymore, like when a user picks a different story before the previous request is done.
🌐
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 - This code achieves the same functionality as the Fetch example but with Axios and request cancellation using an AbortController equivalent (axios.CancelToken). Here is the final result. Now you can see how our application has been improved; the browser only handles the last request and cancels any previous requests that were pending before the current one. The AbortController interface is supported by all modern browsers and other HTTP clients such as Fetch or node-fetch.
🌐
Medium
medium.com › @iamyashkhandelwal › how-to-cancel-api-requests-using-axios-in-javascript-1b6d42084b43
How to cancel API requests using Axios in Javascript? | by Yash Khandelwal | Medium
July 29, 2023 - You just need to modify the Step-2 above and include a timeout option in your API request. ... axios .get('https://api.example.com/data', { cancelToken: source.token, timeout: timeoutDuration || 2000, // time in ms }) .then((response) => { // Process the response data here }) .catch((error) => { if (axios.isCancel(error)) { console.log('Request canceled:', error.message); } else if (error.code === 'ECONNABORTED') { // timeout handling console.log('Request timed out'); } else { console.log('Error:', error.message); } });
🌐
GitHub
github.com › axios › axios › issues › 80
Is it possible to cancel axios requests? · Issue #80 · axios/axios
July 23, 2015 - I'm building something similar to search lookahead, and with each change event to a text input I want to fire off a new set of axios get requests. When the change event occurs, I need to cancel all uncompleted axios requests from the last change event (as they will no longer be needed)...
Author   paulwehner
🌐
Reddit
reddit.com › r/reactjs › how to cancel all setstate and axios calls when component unmounts
r/reactjs on Reddit: How to cancel all setState and axios calls when component unmounts
August 4, 2022 -

I have this component with the function getAnswer When user clicks the button, the getAnswer will fetch the question's answer from the backend, sets the fetched answer to local useState, and make another POST request back to the backend.

The problem is I get the good old "cannot reform state update on unmounted component" and "400 request error" when user moves to another page.

next-dev.js?3515:25 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

This is the error log; how do I cancel ALL axios requests and setState requests inside the getAnswer function when the component is unmounted?

export const SingleQuestion = ({ question }: { question: Question }) => {
  const [answer, setAnswer] = useState('');
  const [answered, setAnswered] = useState(false);
  const [isAnswerLoading, setIsAnswerLoading] = useState(false);

  const getAnswer = async () => {
    // prevent fetch when user is generating more questions
    setIsAnswerLoading(true);
    const GPTResponse = await axios.post(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/nlp/questions/`,
      {
        prompt: question.question,
      },
      { withCredentials: true }
    );
    const parsed = JSON.parse(GPTResponse.data);
    setAnswer(parsed.choices[0].text);
    setAnswered(true);
    await axios.patch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/v1/questions/${question.id}/`,
      { answer: parsed.choices[0].text, answered: true },
      { withCredentials: true }
    );
    setIsAnswerLoading(false);
  };

    return (
      <motion.ul variants={variants} initial="hidden" animate="show">
          <button
            onClick={getAnswer}
          >
            Answer Question
          <button/>
      </motion.ul>
  );
🌐
Medium
medium.com › @velja › cancelling-duplicate-requests-with-axios-076813d3a343
Cancelling Duplicate Requests with Axios | by Veljko Ilić | Medium
July 15, 2024 - Axios makes cancelling requests straightforward with the use of the CancelToken source. By incorporating interceptors, we can enhance this functionality to manage and cancel requests dynamically.