简体   繁体   中英

Axios cancel Request shows browser alert

Axios cancel Request shows browser alert which stops the execution until you click ok. I want to cancel my requests, all my Api calls are in separate file named apiCalls.js .

Component with cancelToken.

componentDidMount() {
        const CancelToken = axios.CancelToken;
        // create the source
        this.source = CancelToken;
    }

    persistCancel = (cancel) => {
        this.setState({cancels: [...this.state.cancels, cancel]})
    }

    componentWillUnmount(){
        this.state.cancels.forEach((c) => c());
    }

this is my Api call from component.

getScoreCardCall({profileId, campaignIds, startDate, endDate}, (scoreCards) => {
            //success
            this.setState({
                scoreCards,
                showComcardsLoader: false
            })
        },this.source,this.persistCancel);

and in the apiCalls.js

export function getScoreCardCall(params,callback, source,onRequest){
    axios.get(url,
        {
        cancelToken: new source(function executor(c) {
            onRequest(c);
            }),
        params:{
            profileId: params.profileId,
            campaignId: params.campaignIds.toString(),
            startDate: params.startDate,
            endDate: params.endDate,
        }
        })
    .then(res => {
        if(callback != null){
            if(res.data.length!=0){
                callback(res.data);
            }
        }
    })
    .catch(err => {
        if (axios.isCancel(err)) {
            console.log(err.message);
          }
    })
}

警报

Can someone please tell me why is alert showing with every request cancellation?? or what i am doing wrong?

axios#cancellation describes two ways to use the cancelToken. You used the first way, with source.token/source.cancel. I started out that way, and had a similar problem as yours: Once a request to a particular URL was canceled, I could never get a successful response from that URL again. I switched to the second method using an executor function and the problem went away. I guess was sharing the same cancelToken for multiple requests, which is what they say you can do with the executor function method. Anyway, maybe that would work for you too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM