AXIOS客户端对我的useMutation的错误响应出现问题.

Axios客户端

import axios from "axios";

const client = axios.create({ baseURL: `${process.env.REACT_APP_API_HOST}/${process.env.REACT_APP_API_PREFIX}` });

export const request = ({...options}) => {
    client.defaults.headers.common.Authorization = `Bearer ${JSON.parse(localStorage.getItem('userDetails')).idToken}`
    client.defaults.headers.common['Content-Type'] = 'application/json';
    const onSuccess = (response) => {
        console.log('AXIOS !!!!! request Successful!!!', response.config.url)
        return response;
    };

    const onError = error => {
        console.error('AXIOS !!!!!  Request Failed:', error.config.url);
        return error
    };

    return client(options).then(onSuccess).catch(onError);
}

这是我的useMutatuon文件

import { useMutation, useQueryClient } from 'react-query';
import {request} from '../utils/axios';

const useAddInvestmentAction = (investment)  => {
    // Define the headers object
    return request({ 
        url: '/investments/investment1', 
        method: 'post', 
        data: investment,
    })
}


export const useAddInvestmentData = () => {
    const queryClient = useQueryClient()
    return useMutation(useAddInvestmentAction,{
        onSuccess: () => {
            queryClient.invalidateQueries('InvestmentsData')
            console.log('Investment Added Successfully!!!!!!!!!!!!!!!!!')
        },
        onError: (error) => {
            console.log('Investment Failed!!!!!!!!!!!!!!!!!')
            console.log(error)
        }
    })
}

export default useAddInvestmentData;

当我将URL更改为不存在URI时,我的onSuccess触发器而不是onError.Axios在错误上打印

知道为什么吗

推荐答案

您需要从catch块抛出一个错误.此外,请记住,类似thencatch块返回promise ,除非抛出错误.

    const onError = error => {
        console.error('AXIOS !!!!!  Request Failed:', error.config.url);
        throw new Error('error_mesage') // <- this is the change
    };

Reactjs相关问答推荐

有正确的方法来设置我的金牛座应用程序的图标吗?

安装后未渲染tailwind

有没有一种惯用的方式来接受特定的子元素?

使用`Link`包装`tr`标记会在Next.js中产生水合错误14

React Router:在没有手动页面刷新的情况下,路由不会更新内容

这两个子元素在Reaction Native中使用的有什么不同?

无法使用 Suspense 和 Await 获取数据

如何在 TimePicker 中更改时钟 colored颜色 和确定按钮字体 colored颜色 - MUI React

React-router动态路径

useState数组不更新

即使配置了 webpack.config.js,html-loader 也不起作用

损坏的图像 React useState

React - 添加了输入数据但不显示

如何实现 redux 工具包来注册用户?

为什么 setState 在 React 中不是异步的?

如何在不重新加载页面的情况下加载新添加的数据?

将 ref 转发到所有页面(路由组件)只是为了将其应用于
并具有跳过导航链接(按钮).有没有更好的办法?

如何使用 React Hook Form 将寄存器作为 props 发送到子组件来收集数据?

如何在 React JS 上使文本中的单词可点击

为什么我在运行一些 npm react 命令时会收到这些警告?