You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Query中API错误响应被判定为成功的问题排查

解决React Query中useMutation始终触发onSuccess的问题

你的问题根源在于callAxios函数的错误处理逻辑——在catch块中直接返回了错误对象,导致Promise始终处于**resolved(成功)**状态,React Query会将所有请求判定为成功,因此即便API返回错误,useMutation的onSuccess仍会被调用。

解决方案

修改callAxios的错误处理逻辑,将catch块中的return err改为throw err,让Promise进入**rejected(失败)**状态,这样React Query才能正确识别错误并触发onError回调。

修改后的callAxios代码

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>) => {
            // 可选:如果需要根据HTTP状态码自定义错误判断
            if (res.status >= 400) {
                throw new Error(`请求失败,状态码:${res.status}`);
            }
            return res
        })
        .catch(err => {
            // 抛出错误,使Promise进入rejected状态
            throw err;
        })
}

额外说明

  • 如果接口返回HTTP状态码为200但包含业务错误(比如返回code: 500),可以在then块中添加业务逻辑判断,不符合成功条件时主动抛出错误。
  • 修改后,useMutation的onError会在API请求失败时正常触发,onSuccess仅在请求真正成功时执行。

内容的提问来源于stack exchange,提问作者Nischal047

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:55:27