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

TypeScript中如何从Axios AsyncThunk获取错误响应数据

解决TypeScript中Axios AsyncThunk错误响应数据访问问题

在TypeScript中,catch块捕获的错误默认类型是unknown,这是TypeScript的安全机制,所以你不能直接访问error.response这类属性。以下是合规且类型安全的解决方案:

步骤1:导入AxiosError类型

先从axios中导入AxiosError类型,用于做类型守卫:

import { AxiosError } from 'axios';

步骤2:定义后端错误响应的类型

明确后端返回的错误数据结构:

interface BackendErrorResponse {
  error: string;
}

步骤3:在catch块中添加类型守卫

通过类型守卫确认错误是AxiosError实例,并且存在响应数据,再安全访问错误信息:

export const registerClient = createAsyncThunk('clients/register', async (userData: object, { rejectWithValue }) => {
  try {
    const response = await axiosInstance.post('/web/client/register', userData);
    return response.data;
  } catch (error) {
    // 先判断是否为AxiosError,且存在响应及响应数据
    if (error instanceof AxiosError && error.response?.data) {
      // 断言响应数据为我们定义的错误类型
      const errorData = error.response.data as BackendErrorResponse;
      return rejectWithValue(errorData.error);
    }
    // 处理非Axios错误的情况
    return rejectWithValue('请求发生未知错误');
  }
});

为什么之前的方法无效?

  • 直接用as any能绕过类型检查,但违背了TypeScript的类型安全原则,不推荐。
  • 直接将error.response.data赋值给ErrorResponse类型时,因为error是unknown,TypeScript无法确认它具备response属性,必须先通过instanceof AxiosError做类型守卫,缩小错误的类型范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 17:17:11