【发布时间】: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