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

使用react-hook-form的useForm钩子时出现Invalid Hook Call错误

React Hook Form useForm钩子触发Invalid Hook Call错误排查

在开发注册组件时,Register函数组件内初始化useForm<RegisterFormData>()钩子后,触发了Invalid Hook Call错误,错误提示如下:

Hooks can only be called inside of the body of a function component

已知可能原因之一是React与渲染器版本不匹配,相关代码如下:

import { useForm } from "react-hook-form";

type RegisterFormData = {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
  confirmPassword: string;
};
const Register = () => {
  const { register } = useForm<RegisterFormData>();
  console.log(register);
  return (
    <form className="flex flex-col gap-5">
      <h2 className="text-3xl font-bold">Create an Account</h2>
      <div className="flex flex-col gap-5 md:flex-row">
        <label className="text-gray-700 text-sm font-bold">
First Name
          <input className="border rounded w-full py-1 px-2 font-normal"></input>
        </label>
        <label className="text-gray-700 text-sm font-bold">
          Last Name
          <input className="border rounded w-full py-1 px-2 font-normal"></input>
        </label>
      </div>
    </form>
  );
};

错误栈追踪截图:
错误栈追踪

可能的原因及解决步骤

1. React与react-dom版本不匹配

React和其渲染器(如react-dom)必须保持版本一致,否则会触发钩子调用错误。

  • 执行命令查看当前依赖版本:
    npm list react react-dom
    
  • 若版本不一致,更新至同一版本,例如:
    npm install react@latest react-dom@latest
    

2. 组件未以React组件方式渲染

确保Register组件是通过JSX语法渲染(<Register />),而非直接调用普通函数Register(),后者会导致钩子调用不符合规则。

3. 钩子调用位置不符合规则

确认useForm始终在组件函数的最顶层执行,未被包裹在条件判断、循环语句或嵌套函数内——这是React钩子的核心规则之一。

4. 项目存在多个React实例

若项目中同时存在多个React版本(比如依赖包自带了React),会导致钩子调用异常:

  • 删除node_modules和package-lock.json(或yarn.lock)
  • 重新执行npm install(或yarn install)

5. react-hook-form版本与React不兼容

不同版本的react-hook-form对React版本有要求,需确认使用的react-hook-form版本支持当前React版本,调整至兼容版本即可。

内容的提问来源于stack exchange,提问作者Nikhil sharma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:58:30