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

使用electron-react-boilerplate时触发Invalid hook call错误求助

问题排查:Electron-React-Boilerplate中Invalid Hook Call错误

错误信息

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

已确认信息

  • React与react-dom版本均为18.2.0,版本匹配
  • 组件函数已改为大驼峰命名(Index),符合React组件规范
  • Hooks调用在函数组件内部,未违反Hook规则

可能原因及解决办法

1. 渲染进程存在多份React副本

Electron主进程与渲染进程环境隔离,pnpm的依赖提升机制异常或重复安装可能导致渲染进程加载多份React实例。

  • 删除依赖目录和锁文件:
    rm -rf node_modules pnpm-lock.yaml
    
  • 重新安装依赖:
    pnpm install
    
  • 再次执行pnpm ls react,确保只有根目录下的18.2.0版本React。

2. Ant Design适配问题

Ant Design版本若与React 18不兼容,或引入方式不当可能触发Hook错误:

  • 改用按需引入方式:
    import Card from 'antd/es/card';
    import 'antd/es/card/style';
    
  • 确认Ant Design版本为5.x及以上(React 18适配版本)。

3. Webpack配置未锁定React路径

Electron-React-Boilerplate的Webpack配置可能存在模块解析歧义,需手动指定React路径:

  • 在webpack.renderer.config.js的resolve.alias中添加配置:
    resolve: {
      alias: {
        'react': path.resolve(__dirname, 'node_modules/react'),
        'react-dom': path.resolve(__dirname, 'node_modules/react-dom')
      }
    }
    
  • 重启开发服务:pnpm dev

4. 排查全局React注入冲突

查看组件中window.React的控制台输出,若与本地安装的React版本不一致,说明存在外部注入的React实例(如预加载脚本、第三方插件),需排查并移除该注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 22:05:37