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

注册页面点击Register按钮报错TypeError: Cannot read properties of undefined (reading 'data')

解决TypeError: Cannot read properties of undefined (reading 'data')问题

问题根源

你遇到的错误是因为axios请求失败时,并非所有错误场景都会返回response对象:

  • 当出现网络故障、请求超时、后端服务器无响应这类情况时,err.response会是undefined
  • 直接访问err.response.data就会触发"Cannot read properties of undefined"类型错误

修复代码

修改handleClick中的错误处理逻辑,先判断err.response是否存在,再处理不同类型的错误:

const handleClick = async e => {
    e.preventDefault();

    try{
      await axios.post("http://localhost:8800/api/auth/register", inputs);
    } catch (err) {
      // 区分后端返回的错误和其他类型错误
      if (err.response) {
        // 后端返回了错误响应(比如4xx/5xx状态码)
        setErr(err.response.data);
      } else {
        // 网络错误或服务器无响应
        setErr("网络连接失败,请检查服务器是否运行");
      }
    }
};

额外优化建议

  • 错误显示优化:如果后端返回的data是对象,直接渲染会显示[object Object],可以改成提取具体错误信息(假设后端返回格式为{ message: "错误提示" }):
    setErr(err.response.data.message);
    
  • 前端表单验证:在提交前增加基础验证(比如邮箱格式、密码长度),避免无效请求发送到后端
  • 输入时清除错误:在输入框变化时清除错误提示,提升用户体验:
    const handleChange = (e) => {
        setInputs(prev => ({...prev, [e.target.name]: e.target.value}));
        setErr(null); // 输入时清除错误
    };
    

内容的提问来源于stack exchange,提问作者Lama Dev Student

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:47:02