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

React中使用toast.error展示Async Thunk登录错误消息失效问题

异步登录Thunk错误消息不显示的修复方案

问题排查与修复点:

1. Catch分支未覆盖所有错误场景

原代码仅处理了AxiosError类型的错误,若出现非Axios错误(比如网络中断、运行时异常),catch块没有返回rejectWithValue,会导致rejected action的payload为undefined,无法触发错误消息赋值逻辑。

修改后的Thunk代码:

export const loginThunk = createAsyncThunk(
  'login',
  async (credentials: { email: string; password: string }, { rejectWithValue }) => {
    try {
      const res = await api.post('/api/login', credentials)
      return res.data
    } catch (error) {
      // 处理Axios请求错误
      if (error instanceof AxiosError) {
        // 优先取后端返回的错误数据,无数据则用Axios自带错误信息
        const errorInfo = error.response?.data || error.message
        return rejectWithValue(errorInfo)
      }
      // 兜底处理所有其他错误类型
      return rejectWithValue(error instanceof Error ? error.message : '登录失败,请稍后重试')
    }
  }
)

2. 错误数据结构判断逻辑太局限

后端返回的error.response?.data大概率是对象(比如{ message: '邮箱或密码错误' }),原代码仅判断typeof errorMsg === 'string',会直接忽略对象类型的错误信息,导致错误消息无法展示。

修改后的reducer分支:

builder.addCase(loginThunk.rejected, (state, action) => {
  const errorPayload = action.payload
  // 兼容字符串、带message属性的对象两种常见错误格式
  if (typeof errorPayload === 'string') {
    state.error = errorPayload
  } else if (errorPayload && typeof errorPayload === 'object' && 'message' in errorPayload) {
    state.error = errorPayload.message
  } else {
    // 兜底默认错误提示
    state.error = '登录失败,请稍后重试'
  }
  state.isLoading = false
  // Redux Toolkit的Immer会自动处理状态更新,无需return state
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:25:10