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

React Formik中出现‘branch is not a function’错误的原因排查

Yup验证报错"Uncaught (in promise) TypeError: branch is not a function"的原因及修复

错误原因

这个报错的核心问题在于**endHour的when方法使用方式不符合Yup的规则**:

  • 你在Yup.date()后直接链式调用when,并在函数里返回修改后的schema,这种写法会干扰Yup内部的分支处理逻辑,导致branch函数未被正确初始化。
  • 另外,原代码外层将schema包裹在数组中导出,Formik需要接收单个schema对象而非数组,这也是潜在的触发错误的因素。

修复后的代码

import * as Yup from "yup";
import checkout from "./form";

const {
  formField: {
    description,
    daysOfWeek,
    daysOfWeek: { startHour, endHour, dayName, isWorkDay },
  },
} = checkout;

export default Yup.object().shape({
  [description.name]: Yup.string().required(description.requiredMessage),
  daysOfWeek: Yup.array().of(
    Yup.object().shape({
      [dayName.name]: Yup.string(),
      [isWorkDay.name]: Yup.bool(),
      [startHour.name]: Yup.date().when(isWorkDay.name, {
        is: true,
        then: Yup.date()
          .typeError(startHour.invalidMsg)
          .required(startHour.requiredMessage),
        otherwise: Yup.date().nullable(),
      }),
      [endHour.name]: Yup.when([isWorkDay.name, startHour.name], {
        is: (isWorkDayVal) => isWorkDayVal,
        then: Yup.date()
          .typeError(endHour.invalidMsg)
          .min(Yup.ref(startHour.name), endHour.dateDifference)
          .required(endHour.requiredMessage),
        otherwise: Yup.date().nullable(),
      }),
    })
  ),
});

关键修改说明

  1. 移除外层数组包裹,直接导出Yup.object().shape()生成的schema对象,符合Formik的接收要求。
  2. 将endHour的Yup.date().when()改为Yup.when()直接调用,避免链式调用破坏Yup的分支处理逻辑。
  3. 使用Yup.ref(startHour.name)替代直接传入参数值,确保验证时能动态获取最新的startHour字段值,避免出现静态值失效的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:12:33