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

Yup条件验证触发branch is not a function错误的原因及解决方法

错误原因及修复方案

错误原因

这个branch is not a function错误几乎都是Yup条件验证(when方法)的写法不符合API规范导致的,常见场景包括:

  1. 在when的then/otherwise分支中直接赋值Schema实例,而非通过回调函数返回Schema(Yup内部需要通过回调来处理分支逻辑,直接赋值会破坏其内部流程)。
  2. 嵌套对象的条件验证中,没有正确引用父级字段的路径(比如riskClassification是根字段,而investigationType在safetyDetail嵌套对象里,路径引用错误会导致Yup无法获取依赖字段,触发内部逻辑报错)。
  3. 误用了未定义的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 00:09:22