I guess it doesn't work because you are trying to cancel the wrong token.

Let's look at this example:

export default function Home() {
  let axiosCancelToken;

  async function getData() {
    if (axiosCancelToken) {
      axiosCancelToken.cancel();
    }

    axiosCancelToken = axios.CancelToken.source();

    let val = await axios({
      method: "GET",
      url: "https://jsonplaceholder.typicode.com/todos/1",
      cancelToken: axiosCancelToken.token
    });
  }

  return (
    <div>
      <button onClick={getData}>Get Data</button>
    </div>
  );
}

Try clicking the button twice quickly, you will see the first request canceled as expected.

But if I change the code by adding some React state, it won't work anymore:

export default function App() {
  let axiosCancelToken;
  let [count, setCount] = useState(0);

  async function getData() {
    setCount((count) => count + 1);

    if (axiosCancelToken) {
      axiosCancelToken.cancel();
      console.warn("request cancelled");
    }

    axiosCancelToken = axios.CancelToken.source();

    let val = await axios({
      method: "GET",
      url: "https://jsonplaceholder.typicode.com/todos/1",
      cancelToken: axiosCancelToken.token
    });
  }

  return (
    <div>
      <button onClick={getData}>Get Data {count}</button>
    </div>
  );
}

And the reason for that is that when React has to re-render, it will call your function component again, where your axiosCancelToken will be instantiated again in the new scope.

To solve this you can just use React Refs.

let axiosCancelToken = useRef();

Answer from User 28 on Stack Overflow
🌐
Axios
axios-http.com › docs › cancellation
Cancellation | Axios Docs
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.');
Discussions

reactjs - how to cancel/abort ajax request in axios - Stack Overflow
I use axios for ajax requests and reactJS + flux for render UI. In my app there is third side timeline (reactJS component). Timeline can be managed by mouse's scroll. App sends ajax request for the More on stackoverflow.com
🌐 stackoverflow.com
Cancel axios get request when typing reactjs - Stack Overflow
I'm creating an autocomplete function, so basically whenever I type on search box it will cancel the previous http get request. I checked the jQuery ui autocomplete and that's what they did. Is that More on stackoverflow.com
🌐 stackoverflow.com
August 7, 2019
How to cancel token using a custom Axios instance?
I have an custom Axios instance using axios.create(). I would like to use the cancellation feature of Axios but the request fired from custom instance never gets cancelled. It does't get detect... More on github.com
🌐 github.com
13
June 11, 2020
Axios Post Request not firing with cancelToken
Describe the issue Hi I am calling two messages. One to create my Axios cancelToken and then one to upload a file. The upload file was working up until I added the cancelToken but I still cannot ge... More on github.com
🌐 github.com
5
October 8, 2020
🌐
DEV Community
dev.to › tmns › usecanceltoken-a-custom-react-hook-for-cancelling-axios-requests-1ia4
useCancelToken: a custom React hook for cancelling Axios requests - DEV Community
January 26, 2022 - Then, along with our request we send an extra piece of data, cancelToken, containing our source's token. However, this alone still doesn't accomplish our goal of cancelling on unmount!
🌐
Andrewevans
andrewevans.dev › blog › 2021-08-11-how-to-use-axios-cancel-tokens-with-react-redux
How to use Axios Cancel Tokens with React Redux
To better improve that experience, you can use Axios Cancel Tokens to allow the user to cancel the HTTP call after it has started. If you’re working with a React Redux application, this might not be quite as straightforward since you’re using effects to handle your HTTP calls rather than local state with useEffect setup.
🌐
GitHub
github.com › AXeL-dev › react-use-cancel-token
GitHub - AXeL-dev/react-use-cancel-token: A handy react hook to cancel axios requests | https://axel-dev.github.io/portfolio/blog/post/react-cancel-axios-requests-the-right-way
import * as React from 'react'; import axios from 'axios'; import { useCancelToken } from 'react-use-cancel-token'; const Example = () => { const { newCancelToken, cancelPreviousRequest, isCancel } = useCancelToken(); const handleClick = async () => { cancelPreviousRequest(); try { const response = await axios.get('request_url', { cancelToken: newCancelToken(), }); if (response.status === 200) { // handle success } } catch (err) { if (isCancel(err)) return; console.error(err); } }; return <button onClick={handleClick}>send request</button>; }; Property ·
Author   AXeL-dev
🌐
GitHub
github.com › axios › axios
GitHub - axios/axios: Promise based HTTP client for the browser and node.js · GitHub
3 hours ago - const controller = new AbortController(); axios .get("/foo/bar", { signal: controller.signal, }) .then(function (response) { //... }); // cancel the request controller.abort(); You can also cancel a request using a CancelToken.
Starred by 109K users
Forked by 11.6K users
Languages   JavaScript 89.7% | TypeScript 8.2% | HTML 2.1%
🌐
npm
npmjs.com › package › react-use-cancel-token
react-use-cancel-token - npm
May 11, 2022 - import * as React from 'react'; import axios from 'axios'; import { useCancelToken } from 'react-use-cancel-token'; const Example = () => { const { newCancelToken, cancelPreviousRequest, isCancel } = useCancelToken(); const handleClick = async () => { cancelPreviousRequest(); try { const response = await axios.get('request_url', { cancelToken: newCancelToken() }); if (response.status === 200) { // handle success } } catch (err) { if (isCancel(err)) return; console.error(err); } }; return <button onClick={handleClick}>send request</button>; }; MIT © AXeL-dev ·
      » npm install react-use-cancel-token
    
Published   May 11, 2022
Version   1.0.3
Author   AXeL-dev
Find elsewhere
🌐
Medium
medium.com › @ali.abualrob2612 › optimizing-your-apps-with-axios-cancel-tokens-a-simple-guide-d27fbdbf4ada
Optimizing your Apps with Axios Cancel Tokens: A Simple Guide | by Ali Abualrob | Medium
October 7, 2024 - Without proper management, unnecessary ... HTTP client, provides a feature called Cancel Tokens that allows you to cancel network requests when they are no longer needed....
🌐
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 - We can use the useRef hook in React ... an existing request. If there is, we cancel it. We do this by calling cancel() on the current cancelTokenSource....
🌐
CodingDeft
codingdeft.com › posts › axios-cancel-previous-request-react
Cancelling previous requests in Search bar using Axios in React | CodingDeft.com
And finally, we are calling the API using Axios by passing the search term. Now if we try searching for cat we will see that 3 different calls made and all 3 responses are logged. We really don't need the previous 2 responses, which we can cancel when the next request is made. ... Note that cancelToken is declared outside the function so that the previous token is retained.
🌐
DEV Community
dev.to › collegewap › cancelling-previous-requests-in-search-bar-using-axios-in-react-3nef
Cancelling previous requests in Search bar using Axios in React - DEV Community
August 21, 2021 - Note that cancelToken is declared outside the function so that the previous token is retained. Now if we try to search, we could see that previous requests are canceled and the result is logged only once.
🌐
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 - To fix, cancel all subscriptions ... of cancelling an axios request, the following steps are involved: Create a variable that will hold the cancel token source let source = axios.CancelToken.source();...
Top answer
1 of 6
36

Since axios v0.15 you can cancel request:

You can also create a cancel token by passing an executor function to the CancelToken constructor:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

For more information please have a look Cancellation. And according to your code:

import React from 'react'
import axios from 'axios';

export function autocompleteSearchTest(value) {
    if (cancel != undefined) {
        cancel();
    }
    return axios.get(`https://jqueryui.com/resources/demos/autocomplete/search.php`, {
        cancelToken: new CancelToken(function executor(c) {
            // An executor function receives a cancel function as a parameter
            cancel = c;
        }),
        params: {
            q: value
        }
    })
        .then(response => {
            return response.data.response;
        })
        .catch(error => {
            const result = error.response;
            return Promise.reject(result);
        });
}

var CancelToken = axios.CancelToken;
var cancel;

export class AutoComplete extends React.Component {

    constructor() {
        super()
        this.state = {
            search: ''
        };
        this.handleSearchChange = this.handleSearchChange.bind(this);
    }

    handleSearchChange(event) {
        const target = event.target;
        const value = target.value;
        this.setState({
            search: value
        });
        autocompleteSearchTest(value)
    }

    render() {
        return (
            <div className="App-intro Dialog-section">
                <h2>AutoComplete</h2>
                <div className="form-control">
                    <label htmlFor="password">Lookup :</label>
                    <input name="search" type="text" value={this.state.search}
                           onChange={this.handleSearchChange}
                           id="password" ref="password" placeholder="Enter line"/>
                </div>
            </div>
        )
    }
}

export default AutoComplete;

And here it's

2 of 6
2

use: react, axios and redux-axios-middleware

user actions:

import axios from 'axios';
import * as type from 'constants/user';

const CancelToken = axios.CancelToken;
let cancel;

export const addUser = (data) => {
  if (cancel !== undefined) cancel();

  return ({
    types: [type.ADD_USER_REQUEST, type.ADD_USER_SUCCESS, type.ADD_USER_FAILURE],
    payload: {
      request: {
        url: '/api/user',
        cancelToken: new CancelToken(c => cancel = c),
        method: 'POST',
        data,
      },
    },
  });
};
🌐
GitHub
github.com › robertoachar › react-axios-cancel-token
GitHub - robertoachar/react-axios-cancel-token: React + Axios + Cancel Token
React + Axios + Cancel Token · robertoachar.github.io/react-axios-cancel-token/ react axios token cancellation cancel-token · Readme · MIT license · 1 star · 2 watching · 1 fork · Report repository · No releases published · No packages published · JavaScript 73.9% HTML 26.1% You can’t perform that action at this time.
Author   robertoachar
🌐
GitHub
github.com › axios › axios › issues › 3016
How to cancel token using a custom Axios instance? · Issue #3016 · axios/axios
June 11, 2020 - const axiosAuth = axios.create(); const cancelToken = axios.CancelToken.source(); //request const getProducts = async () => { try { const response = await axiosAuth.get('api', { cancelToken: cancelToken.token }); if (response.status === 200) { return response.data; } } catch (err) { if (axios.isCancel(err)) { console.log('Error: ', err.message); return true; } else { throw new Error(err); } } }; // I'm cancelling the request on button click using `cancelToken.cancel()` Expected behavior, if applicable The request should cancel when used with a Custom Axios instance · Environment: Axios Version 0.19.2 · OS: Ubuntu · Browser: Chrome · Browser Version: 83 · Reactions are currently unavailable ·
Author   FatehAK
🌐
GitHub
github.com › axios › axios › issues › 3323
Axios Post Request not firing with cancelToken · Issue #3323 · axios/axios
October 8, 2020 - export async function postFiles<T>( url: string, postForm: FormData, queryData: {} = {}, handleProgress?: (progress: ProgressEvent) => void, ) { await axios.post(`${apiRoot}/${url}${objToQuery(queryData)}`, postForm, { headers: { 'Content-Type': 'application/json' }, withCredentials: true, onUploadProgress: handleProgress, cancelToken: source.token, }) .then(res => console.log(res)) .catch(thrown => { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } }); if (true) { source.cancel('Request canceled!'); } };
Author   shellac85
🌐
GitHub
github.com › axios › axios › issues › 1714
Cancel several requests with same CancelToken · Issue #1714 · axios/axios
August 7, 2018 - I have different react modules in a view, while each is calling an API via axios. When going to another view, all calls should be cancelled. However, when returning to this view, the calls should be started again (those are in componentDidMount()). ... import axios from 'axios'; let cancel; export var cancelRequest = (message) => { if (cancel) cancel(message); }; export var setCancelToken = (c) => { cancel = c; }; export var CancelToken = axios.CancelToken;
Author   vtni