我已经实现了一个带有错误处理的异步登录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) {
      if (error instanceof AxiosError) {
        return rejectWithValue(error.response?.data)
      }
    }
  }
)

extraReducers: (builder) => {
    //** Login */
    builder.addCase(loginThunk.pending, (state) => {
      state.isLoading = true
    })
    builder.addCase(loginThunk.fulfilled, (state, action) => {
      state.user = action.payload.user
      state.isLoggedIn = true
      state.isLoading = false
    })
    builder.addCase(loginThunk.rejected, (state, action) => {
      const errorMsg = action.payload
      if (typeof errorMsg === 'string') {
        state.error = errorMsg
      }
      state.isLoading = false
      return state
    })
}

推荐答案

createAsyncThunks个突克将会有103个回报一个已解决的promise .onSubmitHandler应该解包由loginThunk动作返回的已解析promise ,以确定该动作是否成功或是否存在错误.

有关详情,请参阅:

您可以处理promise 链中的错误:

const onSubmitHandler = (e: FormEvent) => {
  e.preventDefault();

  dispatch(loginThunk(credentials))
    .unwrap()
    .then((res) => {
      const { message, token } = res.payload;
      localStorage.setItem('token', token);
      toast.success(message);
      navigate('/');
    })
    .catch((error) => {
      let errorMessage = 'Something went wrong';

      if (error instanceof AxiosError) {
        const errorMessage = error.response?.data.msg;
      }

      toast.error(errorMessage);
    });
};

或者在try/catch名中有async/await名:

const onSubmitHandler = async (e: FormEvent) => {
  e.preventDefault()
  try {
    const res = await dispatch(loginThunk(credentials)).unwrap();

    const { message, token } = res.payload;
    localStorage.setItem('token', token);
    toast.success(message);
    navigate('/');
  } catch (error) {
    let errorMessage = 'Something went wrong';

    if (error instanceof AxiosError) {
      const errorMessage = error.response?.data.msg;
    }

    toast.error(errorMessage);
  }
};

Typescript相关问答推荐

无需刷新即可让现场访客逆变

具有映射返回类型的通用设置实用程序

使用ngrok解析Angular 时出现HTTP故障

泛型函数中输入参数类型的推断问题

有没有办法解决这个问题,类型和IntrinsicAttributes类型没有相同的属性?

Angular 错误NG0303在Angular 项目中使用app.Component.html中的NGFor

为什么我的条件类型不能像我预期的那样工作?

Cypress页面对象模型模式.扩展Elements属性

有没有可能产生输出T,它在视觉上省略了T中的一些键?

使用Redux Saga操作通道对操作进行排序不起作用

在打印脚本中使用泛型扩展抽象类

TypeScrip泛型类未提供预期的类型错误

专用路由组件不能从挂钩推断类型

为什么Typescript只在调用方提供显式泛型类型参数时推断此函数的返回类型?

如何使这种一对一关系在旧表上起作用?

任何导航器都未处理有效负载为";params";:{";roomId";:";...";}}的导航操作

仅当类型为联合类型时映射属性类型

Typescript泛型验证指定了keyof的所有键

从 npm 切换到 pnpm 后出现Typescript 错误

如何编写一个接受 (string|number|null|undefined) 但只返回 string 且可能返回 null|undefined 的函数?