解决 模块联邦 报错 Shared module has multiple copies React 规则破坏修复
排查 模块联邦应用报 Warning: Invalid hook call. Hooks can only be called inside of the body of a function component,分析 React 单例共享配置(singleton: true)缺失与版本范围失配。
问题现象
主应用引入子应用的 React 组件并渲染时,控制台抛出经典的 Hook 调用失效红色大框报错:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
触发根因
- 主应用与子应用的构建配置中虽然声明了 shared 依赖,但未配置
singleton: true; - 当主应用与子应用各自安装的 React 次版本号不一致(如 18.2.0 与 18.3.1)时,Webpack 默认各自加载一份独立实例;
- 两个不同版本的 React 内部 Dispatcher 上下文无法互通,导致在子应用组件内执行
useState时抛错。
解决步骤
在主应用与所有子应用的 ModuleFederationPlugin 中将 React 声明为强单例
统一依赖配置:
const deps = require('./package.json').dependencies;
new ModuleFederationPlugin({
shared: {
react: {
singleton: true,
requiredVersion: deps.react,
},
'react-dom': {
singleton: true,
requiredVersion: deps['react-dom'],
},
},
});
对同架构同技术栈的依赖确保 package.json 锁定的语义化版本区间兼容
如使用 ^18.2.0。
在根项目中配置 packageManager resolutions 强制单一版本
杜绝 node_modules 出现嵌套不同版本的 React。
验证确认
重新构建主子应用:
整个运行态仅全局驻留唯一一份 React 运行时单例,子应用 Hook 调用顺畅渲染,多副本冲突彻底消除。


