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

为何函数组件内调用trpc React Hook仍触发无效Hook调用错误?

React钩子调用无效错误排查

我基于electron-trpc的基础React+SuperJSON示例创建了自己的Electron demo,运行时出现以下错误:

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.

错误出现在src/renderer/src/HelloElectron.tsx文件的这一行代码:

const res = trpcReact.greeting.useQuery({ name: 'Electron' }); // 执行此行时报错

明明这段代码写在函数组件内部,为什么还是触发这个错误?


可能的原因及解决办法

1. 项目中存在多份React副本

这是Electron+React场景下最常见的诱因:

  • 检查根目录与renderer子目录的package.json,确认react、react-dom是否同时在两个目录的依赖中被安装
  • 执行npm ls react或yarn list react,查看输出是否存在重复的React包条目
  • 解决方式:将react、react-dom统一安装在项目根目录的依赖中,renderer目录通过peerDependencies声明依赖;或者在renderer的package.json中使用overrides(npm)或resolutions(Yarn)字段,强制统一React版本。

2. React与渲染器版本不兼容

  • 确保react和react-dom的版本完全一致,版本号差一个小版本都可能引发问题
  • 若使用@electron-forge/plugin-react这类集成插件,确认插件依赖的React版本与你项目中安装的版本匹配。

3. tRPC React Provider未正确配置

tRPC的React钩子需要在Provider的上下文环境中才能正常工作:

  • 检查你的组件树顶层是否正确包裹了tRPC Provider和React Query的QueryClientProvider,示例配置如下:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { trpc } from './utils/trpc';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <trpc.Provider client={trpc.client}>
        <HelloElectron />
      </trpc.Provider>
    </QueryClientProvider>
  );
}

如果HelloElectron组件不在这个Provider的包裹范围内,钩子无法获取到必要的上下文,就会触发错误。

4. 组件定义或钩子调用违反规则

  • 确认HelloElectron是标准的函数式组件,而非类组件
  • 检查钩子调用是否违反了React钩子规则:比如不能在条件判断、循环、嵌套函数中调用钩子,必须直接写在函数组件的顶层作用域内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:40:06