Search code examples
reactjsaxioscancellation

Axios not cancelling requests


I am trying to cancel an Axios request that I made in CompnentDidMount() in ComponentWillUnmount() as everyone says to do. However it does not seem to be working. Like at all.

Here is the relevant code from my project:

        //Make API call
        this.setState({ isMounted: true });
        this.axiosCancelSource = Axios.CancelToken.source();
        var result;
        result = await Axios("/api/product", { cancelToken: this.axiosCancelSource.token });
        if (this.state.isMounted) {
            this.setState({ products: result.data.products });
        }

        
        //this.updateList();


    }

    componentWillUnmount() {
        this.setState({ isMounted: false });
        this.axiosCancelSource.cancel();
    }

and here is a snapshot of my network tab in Chrome DevTools: Network Screenshot

I'm not sure if this is the issue, but it seems like my component mounts and unmount once very quickly then mounts again. I'm not quite sure the cause of this either or if it might be affecting the cancellation of my axios requests. I've scoured the internet for hours trying to solve this, so any help is appreciated. Thanks!


Solution

  • From react docs: https://reactjs.org/docs/react-component.html#componentwillunmount

    You should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.

    You should remove the setState from unmount for that weird behavior you mentioned. And then you can verify your axios cancel. However, understand what you are doing - you are trying to cancel any axios call IF ANY IN PROGRESS while unmounting. You need to simulate a long running network call and unmount to test it.