相关疑难解决方法(0)

useEffect 中取消 axios 请求未运行

我正在尝试取消 axios 请求,但只取得了部分成功。当我发出 GET 请求时,我有一个返回 Promise 的函数:

const getCards = (token) => {
  const URL = isDev
    ? "https://cors-anywhere.herokuapp.com/https://privacy.com/api/v1/card"
    : "https://privacy.com/api/v1/card";
  const config = {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    cancelToken: source.token,
  };

  return axios.get(URL, config);
};
Run Code Online (Sandbox Code Playgroud)

我在里面调用这个函数updateCards(),如下所示:

const updateCards = async () => {
  console.log("Updating Cards");

  setCards([]);
  setStarted(true);
  setLoading(true);

  let response = await getCards(token).catch((thrown) => {
    if (axios.isCancel(thrown)) {
      console.error("[UpdateCards]", thrown.message);
    }
  });

  /**
   * response is undefined when we cancel the request on unmount
   */ …
Run Code Online (Sandbox Code Playgroud)

reactjs axios react-hooks

3
推荐指数
1
解决办法
2732
查看次数

标签 统计

axios ×1

react-hooks ×1

reactjs ×1