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

使用react-hook-form开发表单时遇formState空值读取错误求助

解决react-hook-form中TypeError: Cannot read properties of null (reading 'formState')错误

问题场景

使用react-hook-form开发表单时,安装@hookform/error-message@2.0.0后触发错误:TypeError: Cannot read properties of null (reading 'formState'),即使卸载该依赖,报错仍未消失。

Register组件核心代码如下:

import React, { useRef } from "react";
import { useForm } from "react-hook-form";

import { Paper } from "@mui/material";
import LoginInfo from "./loginInfo";
import CustomizedButtons from "./Button";

export default function Register() {
  const defaultValues = {
    fornavn: "",
    password: "",
    repeat_password: "",
    email: ""
  };

  const { control, watch, handleSubmit } = useForm({
    defaultValues
  });

  const password = useRef({});
  password.current = watch("password", "");

  const onSubmitSignIn = async (data) => {
    console.log(data);
  };

  return (
    <Paper elevation={3}>
      <form onSubmit={handleSubmit(onSubmitSignIn)}>
        <LoginInfo control={control} />
        <CustomizedButtons type="submit" label="REGISTER" />
      </form>
    </Paper>
  );
}

问题原因

  1. 代码残留引用:卸载@hookform/error-message后,LoginInfo组件中可能仍保留了对该库的导入或ErrorMessage组件的使用,导致运行时找不到依赖抛出错误。
  2. 版本不兼容:@hookform/error-message@2.0.0与当前使用的react-hook-form版本不匹配,触发内部逻辑错误,即使卸载依赖,缓存的不兼容代码或依赖残留仍会影响运行。

解决方案

步骤1:清理残留代码

检查LoginInfo组件(及其他相关组件),删除所有与@hookform/error-message相关的代码:

  • 移除import { ErrorMessage } from '@hookform/error-message'这类导入语句
  • 删除所有<ErrorMessage />组件的使用

步骤2:清除依赖缓存并重装依赖

执行以下命令彻底清理依赖缓存,确保残留文件被移除:

# npm用户
npm cache clean --force
rm -rf node_modules package-lock.json
npm install

# yarn用户
yarn cache clean
rm -rf node_modules yarn.lock
yarn install

步骤3:替代错误提示方案(可选)

如果需要表单错误提示,可改用react-hook-form内置的formState.errors手动渲染,示例如下(修改LoginInfo组件):

import React from "react";
import { Controller, useFormContext } from "react-hook-form";
import { TextField } from "@mui/material";

export default function LoginInfo({ control }) {
  const { formState: { errors } } = useFormContext();

  return (
    <>
      <Controller
        name="fornavn"
        control={control}
        rules={{ required: "请输入名字" }}
        render={({ field }) => (
          <TextField
            {...field}
            label="名字"
            error={!!errors.fornavn}
            helperText={errors.fornavn?.message}
            fullWidth
            margin="normal"
          />
        )}
      />
      {/* 其他表单字段类似处理 */}
    </>
  );
}

注意:使用useFormContext需要在父组件(Register)中用<FormProvider>包裹表单,或者直接从useForm中解构errors并传递给LoginInfo组件。

步骤4:版本兼容(如需重新使用@hookform/error-message)

如果要继续使用@hookform/error-message,需确保其版本与react-hook-form版本匹配:

  • 查看react-hook-form官方文档,确认对应版本的@hookform/error-message兼容范围
  • 安装兼容版本,例如:
# 假设当前react-hook-form为7.x,安装兼容的@hookform/error-message版本
npm install @hookform/error-message@^2.0.1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:10:36