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

GraphQL mutation嵌套对象传参提示必填变量未提供报错求助

问题场景

编写GraphQL mutation实现商家创建功能,初始实现代码如下:

export const CREATE_BUSINESS = gql`
    mutation createBusinessMutation(
        $name: String!
        $website: String!
        $streetAddress: String!
        $city: String!
        $countryCode: String!
        $postCode: String!
    ) {
        business(
            input: {
                name: $name
                number: $number
                website: $website 
                address: {
                    streetAddress: $streetAddress
                    city: $city
                    countryCode: $countryCode
                    postCode: $postCode
                }
            }
        ) {
            id
            name
        }
    }
`;

执行mutation时触发以下报错:

1: {message: "Variable "$streetAddress" of required type "[String]!" was not provided.",…}
2: {message: "Variable "$city" of required type "[String]!" was not provided.",…}
3: {message: "Variable "$countryCode" of required type "[String]!" was not provided.",…}
4: {message: "Variable "$postCode" of required type "[String]!" was not provided.",…}

异常触发规律:仅在参数以嵌套对象形式传入时出现,非嵌套传参可正常运行。

故障原因
  1. 变量类型声明和服务端Schema定义不匹配:mutation头部声明$streetAddress/$city等地址字段为String!(非空单字符串)类型,但服务端Schema中address嵌套对象下的对应字段实际类型为[String]!(非空字符串数组),类型校验不通过时引擎会判定符合类型要求的变量未传入。
  2. 存在未声明的变量:代码中input字段传入了number: $number,但头部变量列表中没有定义$number的类型,会破坏整体变量校验逻辑。
修复方案
  • 对齐变量类型与Schema定义
    核对服务端GraphQL Schema中地址相关字段的实际类型:如果字段确实为[String]!数组类型,将头部变量声明中对应字段的类型从String!修改为[String]!,传参时传入符合格式的字符串数组即可;如果Schema中字段实际为单字符串String!类型,说明本地gql解析缓存的Schema版本和服务端不一致,重新拉取服务端Schema更新本地类型定义即可。
  • 清理/补全变量声明
    移除input中不需要的number字段,或在头部变量列表中补充$number的对应类型定义,消除未声明变量的校验异常。
  • (推荐写法)使用整对象传参避免嵌套类型声明错误
    不需要将嵌套对象的每个字段拆分为独立变量声明,直接将整个入参声明为对应输入类型的变量,从根源避免嵌套字段类型写错的问题,参考实现如下:
export const CREATE_BUSINESS = gql`
    # BusinessCreateInput替换为服务端Schema定义的商家创建入参的实际类型名
    mutation createBusinessMutation($input: BusinessCreateInput!) {
        business(input: $input) {
            id
            name
        }
    }
`;

// 调用mutation时传入的变量结构
const variables = {
  input: {
    name: "测试商家",
    website: "https://example.com",
    number: "SH001", // 不需要该字段可直接删除
    address: {
      // 字段值格式严格和Schema定义对齐:数组类型传数组,单值类型传字符串
      streetAddress: ["科技路88号"],
      city: "深圳",
      countryCode: "CN",
      postCode: "518000"
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 01:06:24