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

基于React状态的Yup条件验证报错:无法读取undefined的reduce属性

问题解决:Yup验证出现Cannot read properties of undefined (reading 'reduce')错误

问题根源

你的验证逻辑顺序和规则冲突导致了内部报错:

  1. 先给字段加了required强制必填,之后又试图用when把字段设为nullable,两个规则互相矛盾
  2. when的then分支直接重新创建yup.number().nullable(),没有继承之前的规则链,导致Yup内部处理时出现未定义项,触发reduce错误
  3. 逻辑上你想实现「timeFramed为true时无需必填」,但当前代码的is条件是当timeFramed为true时才设置nullable,可之前的required规则没被移除,空字段依然会触发必填校验,这种矛盾导致内部崩溃

修正后的代码

ticket: yup
  .number()
  .nullable() // 先允许字段为空
  .when([], {
    is: () => !timeFramedExperience, // 只有当不需要时间限制时,才要求必填
    then: (schema) => schema.required(I18n.t("is_required")),
  }),
max_p: yup
  .number()
  .nullable()
  .when([], {
    is: () => !timeFramed, // 同理,非timeFramed状态下才必填
    then: (schema) => schema.required(I18n.t("is_required")),
  }),

关键调整点

  • 先设置nullable(),让字段默认允许为空
  • 把required规则放到when的then分支,仅当timeFramed(或timeFramedExperience)为false时才启用必填校验
  • when的then分支使用传入的schema参数链式调用,保持规则连贯性,避免重新创建验证实例导致的内部错误
  • 确保当timeFramed状态变化时,验证schema会重新生成(比如把schema创建放在组件内部,依赖timeFramed状态),这样when的判断会实时更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:35:29