【问题标题】:Defining a variable inside the try block of the useQuery function (tanstack's react-query)在 useQuery 函数的 try 块内定义一个变量(tanstack 的 react-query)
【发布时间】:2022-08-19 19:59:32
【问题描述】:

我遇到了一个奇怪的问题,我无法在其中定义了 try catch 块的匿名函数中定义变量。

  let response: AxiosResponse<CustomType[]>;  // had to define outside the useQuery
  const { data: info } = useQuery(
    [\'queryKey\', a, b],
    async () => {
     // let response: AxiosResponse<CustomType[]>; //ERROR variable response is used before being assigned
      try {
        response = await getAxios().get(`requestURL`);
        const responseFiltered = {};
        response.data.forEach((a) => {
           responseFiltered[a] = a;
         })
        return responseFiltered;
      } catch (error) {
        logger.error({
          meta: { error, response}, // variable used here
        });
      }
    }
  );

不知道为什么它期望在 useQuery 函数之外定义响应变量。

  • 你得到什么样的错误?这是来自 eslint,还是来自打字稿,还是在运行时?此外,您在不存在的 catch 块中使用responseFiltered
  • @TkDodo 感谢您指出这一点。我的意思是在我现在更新的 catch 块中输入它作为响应。这是打字稿错误variable response is used before being assigned

标签: javascript try-catch react-query


【解决方案1】:

您告诉编译器响应的类型为AxiosReponse。但是,您没有在分支中为响应提供“价值”。 response 是在 try/catch 中分配的,所以在 catch 子句中,它可能仍然是 undefined。这就是 TypeScript 试图告诉你的。

要解决此问题,请将您的响应定义为可能未定义:

let response: AxiosResponse<CustomType[]> | undefined

然后你可以在catch 块中使用它。即使,很可能,在 catch 块中将要如果网络请求失败,则为 undefined。

对于 axios,error 实际上是一个 AxiosError,它将包含响应,所以也许你想要这样的东西?

const { data: info } = useQuery(
    ['queryKey', a, b],
    async () => {
        try {
            const response = await axios.get(`requestURL`);
            return response;
        } catch (error) {
            if (axios.isAxiosError(error)) {
                console.error({
                    meta: { error, response: error.response },
                });
            }
            throw error
        }
    }
);

请进一步记住,捕获错误只是为了记录错误对于react-query 来说并不理想,因为它会“吞下”错误。您可以看到我在 catch 块的末尾重新抛出了错误。更好的方法是使用 onError 回调:

const { data: info } = useQuery(
    ['queryKey', a, b],
    async () => {
        return await axios.get(`requestURL`);
    }, {
    onError: (error) => {
        if (axios.isAxiosError(error)) {
            console.error({
                meta: { error, response: error.response },
            });
        }
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 2021-12-08
    • 2022-07-21
    • 1970-01-01
    • 2023-02-07
    相关资源
    最近更新 更多