【问题标题】:Error responses from api are considered success in react query来自 api 的错误响应在反应查询中被认为是成功的
【发布时间】:2023-01-16 00:19:45
【问题描述】:

在 React 查询中,每个响应都被视为成功。

axios用于调用api请求。这是一个 axios 组件。

export const callAxios = async ({
    url,
    method,
    data,
    headers,
    params,
    responseType,
}: CallAxiosAPI) => {

    const config: AxiosRequestConfig = {
        method: method || 'GET',
        url: `${baseUrl}${url}`,
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            Authorization: accessToken !== null ? `Bearer ${accessToken}` : '',
            ...headers,
        },
        data,
        params,
        responseType,
    }
    return axios(config)
        .then((res: AxiosResponse<any, any>) => {
            return res
        })
        .catch(err => {
            return err
        })
}

这是使用 useMutation 的示例

const adjustProfit = useMutation(
        ['adjustProfit'],
        (params: { configurationId: string; configurationPriceId: number; data: IAdjustType }) => {
            return PricingQueries.adjustProfit(
                parseFloat(String(params.configurationId)),
                params.configurationPriceId,
                params.data,
            )
        },
        {
            onSuccess: () => {
                refetch()
            },
            onError: () => {
                toast.error(t(`message.adjust_price_failed`))
            },
        },
    )

即使有错误 onSuccess 被调用。

【问题讨论】:

  • 如果响应的状态码不是 2xx,axios 将默认抛出。删除 catch 块并让 react-query 处理抛出的错误。请注意,您正在返回错误而不是重新抛出它。

标签: reactjs axios react-query


【解决方案1】:

问题是.catch。通过捕获错误,因为你想记录然后不是重新抛出错误,您正在将错误转换为已解决的 Promise。所以你实际上永远不会将错误返回给 useQuery。

修复方法是删除 catch 并使用 onError 回调进行记录,或者在记录后重新抛出错误。

这个问题很常见,我已将其添加到我的常见问题解答帖子中: https://tkdodo.eu/blog/react-query-fa-qs#why-do-i-not-get-errors-

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-25
    • 2023-04-03
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2020-12-01
    • 2021-04-06
    相关资源
    最近更新 更多