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

React Hook Form提交时handleSubmit不触发问题排查

问题排查结果

你的handleSubmit不触发是多个错误叠加导致的,按以下优先级修改即可恢复正常:

  • 第一处核心错误:form的onSubmit回调里没有正确执行RHF的提交函数。handleSubmit(onSubmit)本身返回的是待执行的事件处理函数,你只是声明了它,既没有传入事件对象也没有调用执行,自然不会跑内部逻辑。
  • 第二处错误:name字段的Controller错误剔除了value属性,表单值完全没同步。你写的field: { value, ...otherFieldProps }把RHF用来绑定输入值的value属性单独解构出来丢弃了,TextField输入的内容根本不会写入表单状态,同时该Controller也没有显式绑定control属性。
  • 第三处错误:yup校验规则和实际表单值类型不匹配,就算前面的提交函数执行了,校验不通过也不会进入你写的onSubmit回调。你schema里定义residentialCountry是yup.number().required(),但下拉选项的value全是字符串类型('Ten'/'Twenty'),类型校验直接失败,且你没有配置校验失败的回调,所以看起来没有任何响应。
  • 第四处错误:Reset按钮错误设置了type="submit",点重置也会触发表单提交逻辑,而且你没有给重置按钮绑定表单重置方法。
  • 额外小问题:WSSelectBox组件的TS类型定义里写的是大写Control属性,和实际传入的小写control命名不一致,虽然运行时不报错,但TS校验会出问题。
修正方案

1. 修正form标签的onSubmit绑定

直接把handleSubmit(onSubmit)作为onSubmit的回调即可,不用自己手动包一层preventDefault,RHF内部已经做了默认事件拦截:

<form onSubmit={handleSubmit(onSubmit)}>

如果你确实要在提交前加自定义逻辑,记得调用返回的处理函数、传入事件对象:

<form
  onSubmit={(e) => {
    console.log('原生提交事件触发');
    handleSubmit(onSubmit)(e); // 必须加(e)调用返回的处理函数
  }}
>

2. 修正name字段的Controller绑定

不要把value从field里解构出来丢弃,直接透传所有field属性,补全control绑定:

<Controller
  name="name"
  control={control}
  render={({ field, fieldState }) => (
    <TextField
      fullWidth
      id="sanctions-form-name"
      label="Name"
      variant="outlined"
      helperText={
        <p
          style={{
            position: 'relative',
            left: -13,
            fontSize: 12,
          }}
        >
          Try to enter the full name or part of it. It is possible
          to use original language or the Latin alphabet.
        </p>
      }
      required
      error={!!fieldState.error}
      {...field} // 直接透传所有field属性,不要单独剔除value
    />
  )}
/>

3. 修正yup校验规则的类型匹配

把residentialCountry的校验类型改成string,和下拉选项的实际值类型一致:

const schema = yup
  .object()
  .shape({
    name: yup.string().required(),
    residentialCountry: yup.string().required(), // 改成string类型,匹配下拉选项的字符串value
    initiator: yup.string().required(),
    program: yup.string().required(),
    list: yup.string().required(),
  })
  .required();

4. 修正Reset按钮的逻辑

把Reset按钮的type改成button,绑定RHF的reset方法:

// 先从methods里解构reset方法
const { handleSubmit, control, reset } = methods;

// 按钮部分修改
<Button
  sx={{
    minWidth: '200px',
    color: '#3883FA',
    ['@media (max-width:460px)']: {
      minWidth: '120px',
    },
  }}
  type="button" // 不要使用submit类型
  onClick={() => reset()} // 绑定表单重置逻辑
>
  Reset
</Button>

5. 修正WSSelectBox的类型定义

把大写的Control改成和实际传参一致的小写control,引入RHF的官方Control类型:

import { Control } from 'react-hook-form';
export type SelectBoxProps = {
  label: string;
  id: string;
  data: Array<string>;
  handleSelect: VoidFunction;
  type: string;
  control: Control<any>; // 修正命名和类型定义
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:57:21