使用GraphQL Codegen编译Mutation时出现Cannot read property 'name' of undefined错误
解决GraphQL Codegen报错:Cannot read property 'name' of undefined
问题场景
我有graphql/mutations/session.mutation.gql文件,内容如下:
mutation CreateSession { createSession }
codegen.yml配置文件:
overwrite: true schema: "http://localhost:4000/graphql" documents: "**/*.{gql,graphql}" generates: src/generated/queries.tsx: plugins: - "typescript" - "typescript-operations" - "typescript-react-apollo"
执行命令graphql-codegen --config codegen.yml时触发错误:
Cannot read property 'name' of undefined
注释掉该Mutation后,Codegen编译可正常运行。
问题原因
这个错误核心是后端Schema里的createSession字段返回类型定义有问题:
- 字段未指定明确的返回类型
- 返回的是无名称的匿名类型
- 旧版Codegen对不规范Schema的兼容性不足
解决方案
1. 修正后端Schema的createSession定义
确保createSession有明确、可解析名称的返回类型,示例:
type Mutation { # 返回会话对象 createSession: Session! # 或用标量类型表示操作结果 # createSession: Boolean! } type Session { id: ID! # 其他会话相关字段 }
如果不需要返回具体数据,用Boolean或String这类标准标量类型即可,别留无类型的字段。
2. 更新GraphQL Codegen依赖
旧版Codegen可能存在类型解析bug,更新到最新版本尝试修复:
npm update @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
3. 临时排查:给字段加别名(可选)
如果暂时改不了Schema,试试给查询字段加别名,看能否绕过解析问题:
mutation CreateSession { session: createSession }
内容的提问来源于stack exchange,提问作者Peter Boomsma
相关产品推荐
相关产品推荐

