使用Amplify订阅失败:UndefinedVariable验证错误排查
Amplify GraphQL订阅出现UndefinedVariable错误排查
问题描述
使用Amplify执行GraphQL订阅操作时触发Validation error of type UndefinedVariable: variable not found错误,无法定位具体缺失的变量,重新推送所有代码变更后问题仍未解决。
代码示例
subscription.current = API.graphql( graphqlOperation(subscriptions.onCreatePurchasedPackage, { owner: userInfo.userName, authMode: "AMAZON_COGNITO_USER_POOLS", }) ); observable.current = await subscription.current.subscribe({ next: ({ provider, value }) => console.log({ "onCreatePurchasedPackage changed the provider": provider, "the value": value, }), error: (error) => console.warn(error), });
错误信息
"Validation error of type UndefinedVariable: variable not found"
项目依赖
"dependencies": { "@aws-amplify/ui-react": "^3.2.0", "@testing-library/jest-dom": "^5.16.4", "@testing-library/react": "^13.3.0", "@testing-library/user-event": "^13.5.0", "@types/jest": "^27.5.2", "@types/node": "^16.11.45", "@types/react": "^18.0.15", "@types/react-dom": "^18.0.6", "aws-amplify": "^4.3.27", "aws-appsync": "^4.1.7", "react": "^18.2.0", "react-dom": "^18.2.0", "react-hook-form": "^7.33.1", "react-router-dom": "^6.3.0", "react-scripts": "5.0.1", "typescript": "^4.7.4", "web-vitals": "^2.1.4" },
排查与解决方案
修正
authMode的传递位置:authMode是GraphQL操作的配置项,不属于订阅变量,不能和owner放在同一个参数对象里,正确写法如下:subscription.current = API.graphql( graphqlOperation(subscriptions.onCreatePurchasedPackage, { owner: userInfo.userName, }, { authMode: "AMAZON_COGNITO_USER_POOLS", }) );之前的写法会把
authMode当作订阅变量传递,但你的GraphQL Schema里并没有定义这个变量,这大概率是错误的直接原因。核对订阅Schema与变量名:检查
onCreatePurchasedPackage的GraphQL Schema定义,确认要求的变量名称和你传入的owner完全一致(包括大小写),同时查看本地生成的订阅代码类型定义,确保参数匹配。验证变量值是否有效:在调用订阅前打印
userInfo.userName,确认该值不是undefined或空值,避免传递无效变量。重新生成客户端代码:执行
amplify codegen命令,同步云端Schema变更到本地客户端代码,确保订阅定义和云端一致。
内容的提问来源于stack exchange,提问作者stack
相关产品推荐
相关产品推荐

