简体   繁体   English

使用 Axios 取消之前的 API 请求

[英]Cancelling previous API requests with Axios

I am trying to follow Axios documentation to cancel repeated requests to an URL but while I get no errors the requests aren't being cancelled.我正在尝试按照 Axios 文档取消对 URL 的重复请求,但是虽然我没有收到错误,但请求并没有被取消。 I still can do as many as I want through the following method.我仍然可以通过以下方法做尽可能多的事情。

import axios from 'axios'

getData({commit,state,dispatch}, id){
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();
      axios
      .get("http://15.100.100.100:9999/getData/" + id,{
        cancelToken: source.token
      }).catch(function (thrown) {
        if (axios.isCancel(thrown)) {
          console.log('Request canceled', thrown.message);
        } else {
          console.log("cancel error")
        }
      })
    },

I followed Axios documentation found here https://github.com/axios/axios#cancellation我关注了在这里找到的 Axios 文档https://github.com/axios/axios#cancellation

EDIT: Kaushik Makwana's answer was correct but in my case, instead of saving in a regular variable, i saved it in a state since my axios calls are made in my store.js file.编辑: Kaushik Makwana 的回答是正确的,但在我的情况下,我没有保存在常规变量中,而是将它保存在一个状态,因为我的 axios 调用是在我的 store.js 文件中进行的。

you can set a global variable to store past request.您可以设置一个全局变量来存储过去的请求。

 var source;
    getData({commit,state,dispatch}, id){

              if(source){
                 source.cancel();
              }
              const CancelToken = axios.CancelToken;
              source = CancelToken.source();
              axios
              .get("http://15.100.100.100:9999/getData/" + id,{
                cancelToken: source.token
              }).catch(function (thrown) {
                if (axios.isCancel(thrown)) {
                  console.log('Request canceled', thrown.message);
                } else {
                  console.log("cancel error")
                }
              })
            },

Using inside componentDidMount lifecycle hook:使用内部 componentDidMount 生命周期钩子:

useEffect(() => {
const ourRequest = Axios.CancelToken.source() // <-- 1st step

const fetchPost = async () => {
  try {
    const response = await Axios.get(`endpointURL`, {
      cancelToken: ourRequest.token, // <-- 2nd step
    })
    console.log(response.data)

  } catch (err) {
    console.log('There was a problem or request was cancelled.')
  }
}
fetchPost()

return () => {
  ourRequest.cancel() // <-- 3rd step
}
}, [])

Note: For POST request, pass cancelToken as 3rd argument注意:对于 POST 请求,将 cancelToken 作为第三个参数传递

Axios.post(`endpointURL`, {data}, {
 cancelToken: ourRequest.token, // 2nd step
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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