使用graphql.js构建嵌套类型报错:类型为undefined问题排查
解决GraphQL.js嵌套类型定义报错问题
常见错误原因及解决办法
1. 类型定义顺序颠倒
你大概率是先定义了Statistic类型,再定义GameStatistic类型。JavaScript是从上到下执行代码的,当解析Statistic的dice和wheel字段时,GameStatistic还没被初始化,自然会返回undefined。
解决方法:调整定义顺序,先写GameStatistic,再写Statistic:
const { GraphQLObjectType, GraphQLInt, GraphQLString } = require('graphql'); // 先定义GameStatistic const GameStatistic = new GraphQLObjectType({ name: 'GameStatistic', fields: { totalPlays: { type: GraphQLInt }, winRate: { type: GraphQLString }, totalWinnings: { type: GraphQLInt } } }); // 再定义依赖GameStatistic的Statistic const Statistic = new GraphQLObjectType({ name: 'Statistic', fields: { dice: { type: GameStatistic }, wheel: { type: GameStatistic } } });
2. 未用函数包裹fields处理依赖
如果你的类型之间存在循环引用(比如GameStatistic也需要引用Statistic),直接写对象形式的fields会导致初始化顺序问题。这时候需要用函数包裹fields,延迟字段的解析时机。
示例代码:
const GameStatistic = new GraphQLObjectType({ name: 'GameStatistic', fields: () => ({ // 用函数包裹 totalPlays: { type: GraphQLInt }, winRate: { type: GraphQLString }, totalWinnings: { type: GraphQLInt }, // 如果需要引用Statistic,这里也能正常访问 parentStat: { type: Statistic } }) }); const Statistic = new GraphQLObjectType({ name: 'Statistic', fields: () => ({ // 用函数包裹 dice: { type: GameStatistic }, wheel: { type: GameStatistic } }) });
3. 类型变量名拼写错误
检查你在Statistic里引用的类型名是否和GameStatistic的变量名完全一致,比如不小心写成了GameStats或者gameStatistic(大小写错误),也会导致引用到undefined。
总结
核心问题就是在解析Statistic的字段时,GameStatistic类型还未被正确初始化,只要确保类型定义顺序正确,或者用函数延迟字段解析,就能解决这个报错。
内容的提问来源于stack exchange,提问作者Kaisin Li
相关产品推荐
相关产品推荐

