axios使用 cancel token 取消请求,报错Uncaught (in promise),错误信息为canceled

本文介绍了在项目中使用axios的cancel token取消请求时遇到的Uncaught (in promise)错误。错误信息显示为'canceled'。分析原因是axios取消请求时返回的Promise被拒绝,需捕获并处理错误。解决方案是在axios请求的catch块中添加错误处理代码,以正确处理被取消的请求。

项目场景:

在使用 cancel token 取消axios请求时报错Uncaught (in promise),错误信息为canceled,具体代码如下

    <body>
        <button style="background-color: rosybrown">发送</button>
        <button style="background-color: honeydew">取消</button>
        <script>
            const btns = document.getElementsByTagName('button');
            let cancel = null;
            btns[0].onclick = function () {
                // 发送请求之前,进行状态判断
                if(cancel!=null){
                    cancel()
                }
                axios.get('http://localhost:3000/posts/2', {
                        cancelToken: new axios.CancelToken(function executor(c) {
                            // executor 函数接收一个 cancel 函数作为参数
                            cancel = c;
                        }),
                    })
                    .then(v => {
                        // 请求状态改变之后,将cancel置为null
                        cancel = null;
                    })
          
            };
            btns[1].onclick = function () {
                cancel();
            };
        </script>
    </body>

原因分析:

这是axios请求的返回值是一个promise对象,当请求被取消时会返回一个错误信息的为cancel的结果,需要有对应的错误处理


解决方案:

在请求的最后加上catch函数,进行错误信息的处理

    axios.get('http://localhost:3000/posts/2', {
                        cancelToken: new axios.CancelToken(function executor(c) {
                            // executor 函数接收一个 cancel 函数作为参数
                            cancel = c;
                        }),
                    })
                    .then(v => {
                        // 请求状态改变之后,将cancel置为null
                        cancel = null;
                    })
                    .catch(reason => {
                        console.log(reason.message);
                    });

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值