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

React报react-apollo only supports one definition per HOC错如何解决

问题现象

加载React应用时浏览器抛出如下错误:

invariant.ts:12 Uncaught Invariant Violation: react-apollo only supports one definition per HOC. [object Object] had 0 definitions. You can use 'compose' to join multiple operation types to a component

当前项目依赖版本:

  • @apollo/client: ^3.6.9
  • apollo-server-express: ^3.9.0
  • express: ^4.18.1
  • express-graphql: ^0.12.0
  • graphql: ^16.5.0
错误产生原因

错误核心是传入useQuery的GraphQL内容不符合客户端查询规范:
你在MyComponent里定义GET_HELLO时,gql标签包裹的是服务端GraphQL Schema的类型定义语法(type Query { hello: String }是服务端用来声明接口结构的Schema写法),不是客户端可执行的查询操作。Apollo解析这段gql内容时,找不到任何可执行的query/mutation/subscription操作定义(也就是报错中提到的0 definitions),因此抛出异常。

修复方案
  1. 替换GET_HELLO的内容为合法的客户端查询语句,不要在客户端查询里写Schema类型定义:
// MyComponent 中修改GET_HELLO定义
const GET_HELLO = gql`
  query GetHello {
    hello
  }
`;
  1. 修复组件渲染逻辑,避免直接渲染对象(React不支持直接渲染普通JS对象,直接写{data}会触发额外渲染错误),同时补全加载、错误状态的处理:
const MyComponent: FC<MyComponentProps> = () => {
  const {data, error, loading} = useQuery(GET_HELLO);

  if (loading) return <div className="MyComponent">加载中...</div>
  if (error) return <div className="MyComponent">加载失败:{error.message}</div>

  return (
    <div className="MyComponent">
      返回数据: {data.hello}
    </div>
  )
}
  1. (可选优化)删除App.tsx中未使用的useQuery、gql导入,减少无效代码:
// App.tsx 修改导入部分
import './App.css';
import { ApolloProvider } from '@apollo/client';
import { apolloClient } from './server/apolloClient';
import MyComponent from './components/MyComponent/MyComponent.lazy';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:06:28