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

在Vite模块联邦远程应用中使用react-hook-form devtools遇错求助

在模块联邦远程应用中使用react-hook-form devtools的报错解决思路

问题背景

在基于Vite和vite-plugin-federation搭建的远程应用中使用react-hook-form devtools时,出现如下报错:

__federation_shared_react.js:35 Uncaught TypeError: Cannot read properties of null (reading 'useRef')

推测该问题与react-hook-form devtools仓库的Issue 140相关,已搭建对应示例仓库复现问题。

解决方法与思路

1. 确保React实例全局单例共享

模块联邦下hooks报错的核心原因是React实例不唯一,devtools依赖的React和远程应用使用的React不是同一个实例,导致useRef这类hooks无法获取正确的上下文。
在宿主和远程应用的vite.config.ts中,将react、react-dom配置为单例共享:

// vite.config.ts
import { defineConfig } from 'vite';
import federation from '@originjs/vite-plugin-federation';

export default defineConfig({
  plugins: [
    federation({
      // 其他配置...
      shared: {
        react: { singleton: true, eager: true },
        'react-dom': { singleton: true, eager: true }
      }
    })
  ]
});

注意必须在宿主和远程两端保持完全一致的共享配置,同时确保react和react-dom的版本匹配。

2. 强制devtools复用项目的React实例

避免devtools打包独立的React副本,在远程应用的vite.config.ts中添加别名配置,强制devtools使用项目根目录的React依赖:

// vite.config.ts
import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  resolve: {
    alias: {
      'react': path.resolve(__dirname, './node_modules/react'),
      'react-dom': path.resolve(__dirname, './node_modules/react-dom')
    }
  },
  // 其他插件配置...
});

同时检查package.json中react-hook-form devtools的依赖版本,确保其要求的React版本与项目依赖完全一致。

3. 调整依赖版本适配

查看对应Issue的社区讨论,尝试切换到已知兼容的版本:

  • 降级react-hook-form devtools到Issue中提到的稳定版本
  • 升级vite-plugin-federation到最新版,修复模块联邦共享逻辑的潜在bug

4. 临时调试替代方案

如果上述方法都无法解决,可以尝试在宿主应用中全局引入react-hook-form devtools,利用宿主的React实例来调试远程应用的表单功能,暂时满足调试需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:37:27