首页 > 解决方案 > axios取消令牌取消每个请求

问题描述

我正在尝试实现 cancelToken API,以便每当我向服务器发出请求以获取每次击键的结果时,只有最后一个请求应该得到处理,但是我已经实现了 axios 取消令牌 API,它似乎取消了每个请求,我在这里做错了什么?每次击键都会调用此函数。

getProductLists2 = async () => {


        let formData = new FormData()

        const { start, limit } = this.state

        formData.append('start', start)
        formData.append('limit', limit)

        formData.append('product_title', this.state.searchTitle)
        formData.append('product_sku', this.state.searchSKU)

        let cancel;

        Axios({
            method: 'POST',
            url: BASE_URL + '/listProduct',
            // headers: { 'Content-Type': 'multipart/form-data' },
            data: formData,
            cancelToken: new Axios.CancelToken(c => cancel = c)
        })
            .then(products => {
                if (products && products.data.productList && products.data.productList.length > 0) {
                    this.setState({ productList: products.data.productList, totalProducts: products.data.productTotal })
                }
            })
            .catch(err => toast.error('Something went wrong'))
        console.log(cancel, 'h')
        cancel && cancel()
    }

标签: reactjsaxioscancellationtokensourcecancellation-tokenrequest-cancelling

解决方案


您应该在进行新的 axios 调用之前取消之前的 cancelToken。当你第一次请求时,保存 cancelToken。然后当你发出第二个请求时,检查是否已经存在 cancelToken 并取消它,然后进行第二个 axios 调用。

对 getProductLists2 进行去抖动以限制调用率也可能是一个好主意

我就是这样做的:

    // Cancel the previous axios token if any
    if (this.cancel) this.cancel.cancel();
    // Get a new token
    this.cancel = axios.CancelToken.source();
    axios
        .get(myURL, { cancelToken: this.cancel.token })
        .then((res) => {
          console.log(res.data);
        })
        .catch((error) => { console.log(error); });

推荐阅读