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

使用GraphQL、graphql-request与react-query调用API时反复出现Invalid AST Node错误

解决Error: Invalid AST Node: {}及相关TypeScript错误

核心问题根源

你的GraphQL Codegen配置中设置了documentMode: 'string',这会让生成的查询文档以字符串形式返回,但graphql-request的request方法需要的是解析后的AST节点(DocumentNode),而非原始字符串,这直接导致了Invalid AST Node: {}错误,同时引发TypeScript类型不匹配问题。

解决步骤

1. 修改GraphQL Codegen配置

更新codegen.ts中的documentMode为documentNode,让Codegen生成符合要求的AST节点类型:

import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: 'http://localhost:4000/',
  documents: 'src/**/*.graphql',
  generates: {
    './src/graphql/generated/': {
      preset: 'client',
      config: {
        documentMode: 'documentNode' // 替换原有的string配置
      }
    },
    './schema.graphql': {
      plugins: ['schema-ast'],
      config: {
        includeDirectives: true
      }
    }
  }
}

export default config

2. 重新生成代码

运行你的Codegen命令(通常是npm run codegen或yarn codegen),确保生成最新的类型和文档节点。

3. 验证依赖兼容性

  • 确保安装了正确版本的graphql-request(你的package.json中未列出,建议安装稳定版):
    npm install graphql-request@latest
    
  • 确认GraphQL服务地址正确:检查graphqlRequestClient中的URL是否指向服务的正确端点(例如部分服务使用/graphql路径,需改为http://localhost:4000/graphql)。

补充说明

当documentMode设为string时,Codegen生成的graphql标记函数会返回字符串类型,而graphql-request的request方法虽然表面上支持字符串,但结合Codegen的类型系统时,会导致参数结构异常,最终触发AST节点无效的错误。修改为documentNode后,生成的文档会被预解析为GraphQL AST,完全匹配graphql-request的要求,同时解决TypeScript类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 05:26:05