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

使用Yup与React Hook Form条件验证时出现TypeError报错求助

解决Yup条件验证导致的"Cannot read properties of undefined (reading 'reduce')"错误

这个错误的核心原因是表单初始化阶段,数组内的questions对象可能未包含type字段(或字段值为undefined),导致Yup在执行when条件判断时,内部逻辑尝试对undefined值执行reduce操作而抛出异常。结合你的代码,给出以下修复方案:

1. 优化Yup Schema的when逻辑

将when的is改为函数式判断,兼容type未定义的场景,同时调整otherwise的规则允许字段为空:

const schema = yup.object({
  questions: yup.array().of(
    yup.object().shape({
      subject: yup.string().required('科目为必填项'),
      subLevel: yup.string().required("子级别为必填项"),
      difficultyLevel: yup.string().required("难度级别为必填项"),
      type: yup.string().required("题型为必填项"),
      name: yup.string().required("题目内容为必填项"),
      image: yup.mixed()
        .test('fileType', '无效的文件格式', (value) => {
          if (!value || typeof value === 'string') return true;
          const supportedFormats = ['image/jpeg', 'image/png'];
          return supportedFormats.includes(value[0]?.type);
        }),
      correctOption: yup.string().when("type", {
        // 用函数判断,先确保type存在再比较
        is: (type) => type === "MCQ",
        then: (schema) => schema.required("必须选择正确选项"),
        otherwise: (schema) => schema.notRequired().nullable(),
      }),
    })
  ),
})

2. 确保表单初始化时的默认值完整

在React Hook Form的useForm中,给questions数组的每个对象设置完整的初始结构,避免字段缺失:

const { register, handleSubmit, formState: { errors } } = useForm({
  defaultValues: {
    questions: [
      {
        subject: "",
        subLevel: "",
        difficultyLevel: "",
        type: "",
        name: "",
        image: "",
        correctOption: ""
      }
    ]
  },
  resolver: yupResolver(schema)
});

3. 可选:给type字段添加默认值

在Yup Schema中给type设置默认值,确保字段始终有初始值:

type: yup.string().required("题型为必填项").default(""),

以上方案通过确保type字段在验证时始终有可访问的值,避免了Yup内部因读取undefined而触发的reduce错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:05:10