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

如何用Redux验证登录邮箱与密码?错误输入致API崩溃

问题解决方法

前端代码修复

你的核心问题是异步错误未被正确捕获:login 是异步函数,但你在 handleClick 里调用时没有用 await,导致外层的 try/catch 无法捕获异步错误;同时 login 内部的 catch 只做了 dispatch,没有把错误抛出给上层处理。

修改步骤:

  1. 把 handleClick 改为异步函数,调用 login 时添加 await:
const handleClick = async (e) => {
  e.preventDefault()
  try {
    await login(dispatch, { email, password })
    // 登录成功后再执行跳转
    history.push("/")
  } catch (error) {
    Swal.fire({
      position: 'top-end',
      icon: 'error',
      title: 'Email atau Password tidak sesuai',
      showConfirmButton: false,
      timer: 1500,
    })
  }
}
  1. 在 login 函数的 catch 块中抛出错误,让上层的 try/catch 能捕获到:
export const login = async (dispatch, user) => {
  dispatch(loginStart())
  try {
    const res = await axios.post(BASE_URL + 'auth/login', user)
    dispatch(loginSuccess(res.data))
  } catch (error) {
    dispatch(loginFailure(error))
    // 抛出错误给上层处理
    throw error
  }
}

API端检查

如果输入错误凭证时API真的崩溃(返回500状态码),需要后端修复API逻辑:

  • 验证用户输入时,对于错误的邮箱/密码,应该返回401 Unauthorized或400 Bad Request的合法响应,而不是让服务器崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:23:22