Yup条件验证触发branch is not a function错误的原因及解决方法
错误原因及修复方案
错误原因
这个branch is not a function错误几乎都是Yup条件验证(when方法)的写法不符合API规范导致的,常见场景包括:
- 在
when的then/otherwise分支中直接赋值Schema实例,而非通过回调函数返回Schema(Yup内部需要通过回调来处理分支逻辑,直接赋值会破坏其内部流程)。 - 嵌套对象的条件验证中,没有正确引用父级字段的路径(比如
riskClassification是根字段,而investigationType在safetyDetail嵌套对象里,路径引用错误会导致Yup无法获取依赖字段,触发内部逻辑报错)。 - 误用了未定义的
branch函数(比如代码中误写了自定义分支逻辑但未实现),或者Yup版本过旧导致API不兼容。
修复方案
1. 修正when方法的回调写法
确保then和otherwise是返回Schema的回调函数,同时正确引用父级字段路径:
import * as Yup from 'yup'; const validationSchema = Yup.object().shape({ riskClassification: Yup.string() .oneOf(['Low', 'Medium', 'High']) .required('请选择风险等级'), safetyDetail: Yup.object().shape({ investigationType: Yup.array() // 用../riskClassification引用根级的风险等级字段 .when('../riskClassification', { is: (value) => ['Medium', 'High'].includes(value), // 通过回调接收当前schema,返回修改后的验证规则 then: (schema) => schema.min(1, '风险等级为中/高时,至少选择一项调查类型'), // 非中/高风险时,移除必填要求 otherwise: (schema) => schema.notRequired() }) }) });
2. 另一种写法:在父级对象上做条件验证
如果嵌套结构复杂,也可以直接对safetyDetail整体做条件验证,更清晰:
const validationSchema = Yup.object().shape({ riskClassification: Yup.string() .oneOf(['Low', 'Medium', 'High']) .required('请选择风险等级'), safetyDetail: Yup.object().shape({ investigationType: Yup.array() }) .when('riskClassification', { is: (value) => ['Medium', 'High'].includes(value), then: (schema) => schema .required('请填写安全详情') .shape({ investigationType: Yup.array().min(1, '至少选择一项调查类型').required() }), otherwise: (schema) => schema.notRequired() }) });
3. 额外排查点
- 检查代码中是否存在自定义的
branch函数,若有需确保它正确返回合法的Yup Schema。 - 升级Yup到最新稳定版本,避免旧版本的API兼容问题:
npm install yup@latest # 或 yarn yarn add yup@latest
内容的提问来源于stack exchange,提问作者Steven Davisworth
相关产品推荐
相关产品推荐

