如何取消此axios请求

时间:2020-09-07 21:34:54

标签: javascript reactjs asynchronous axios

当我的浏览器从该组件重定向离开时,出现内存泄漏。所以我需要取消它,但是由于某种原因,我的取消令牌没有任何作用,我想知道为什么。

请看看,下面是我的代码:

  const getBoards = async (**cancelToken**) => {
    try {
      if (localStorage.getItem("token") == null) {
        throw new Error();
      }

      const response = await Axios.get("/boards", config, **{ cancelToken }**);
      setBoards(response.data);
    } catch (e) {}
  };

  useEffect(() => {
    **const request = Axios.CancelToken.source();**
    getBoards(request);
    return () => {
      **request.cancel();**
    };
  }, []);

1 个答案:

答案 0 :(得分:2)

您通过.token属性使用令牌,没有将source()中的整个对象作为令牌传递。来自the documentation

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

将其翻译为您的代码,

getBoards(request);

将会

getBoards(request.token);
// −−−−−−−−−−−−−−^^^^^^