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

React登录页includes()报错:无法读取undefined的includes属性

解决React useReducer中includes()调用的"Cannot read properties of undefined"错误

问题根源

你的错误并非时序问题,而是reducer中属性访问的逻辑错误:

  • 在处理INPUT_BLUR类型的action时,你尝试访问action.value(邮箱校验)和action.value(密码校验),但触发onBlur时dispatch的action只传入了type: 'INPUT_BLUR',没有携带value属性,导致action.value为undefined,调用includes()或trim()时就会抛出错误。
  • 实际上,当触发onBlur时,输入框的最新值已经保存在reducer的state中,完全不需要从action里取值。

修复代码

修改两个reducer中的INPUT_BLUR分支逻辑,改用state.value进行校验:

修复后的emailReducer

const emailReducer = (state, action) => {
  if (action.type === 'USER_INPUT') {
    console.log(action.val);
    return { value: action.val, isValid: action.val.includes('@') };
  }
  if (action.type === 'INPUT_BLUR') {
    // 从state中读取当前值,而非action
    return { value: state.value, isValid: state.value.includes('@') };
  }

  return { value: '', isValid: false };
};

修复后的passwordReducer

const passwordReducer = (state, action) => {
  if (action.type === 'USER_INPUT') {
    return { value: action.val, isValid: action.val.trim().length > 6 };
  }
  if (action.type === 'INPUT_BLUR') {
    // 从state中读取当前值,而非action
    return { value: state.value, isValid: state.value.trim().length > 6 };
  }

  return { value: '', isValid: false };
}

补充说明

你之前用console.log(action.val)能看到值,是因为那是在USER_INPUT分支——这个分支的action确实携带了val属性,但INPUT_BLUR的action没有传递任何额外数据,所以访问action.value必然会得到undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:30:44