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

传递变量时GraphQL Mutation执行失败问题求助

GraphQL Mutation传变量失败问题解决

问题核心

你的请求里variables字段始终是空对象,导致后端接收不到Mutation定义的$state变量,这就是报错的直接原因。硬编码state值时能正常执行,说明Mutation本身逻辑没问题,问题出在变量传递环节。

错误原因分析

你尝试传入的{id: "asd", state: true}包含了已经在Mutation里硬编码的id,但实际上这个Mutation只需要传state变量——因为id和equipmentId已经写死在query中了。更关键的是,这个参数没有被正确放到请求的variables字段里,所以后端依然拿不到$state的值。

正确解决步骤

  1. 传递正确的变量结构:只需要传{state: true},不需要包含id(已硬编码)。
  2. 确保变量绑定到请求的variables字段:
    • 原生Fetch请求示例:
      fetch('/your-graphql-endpoint', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          operationName: 'MUTATE_AddEquipment',
          query: `mutation MUTATE_AddEquipment($state: Boolean!) {
            addEquipment(equipment: {id: "asd", equipmentId: 1, state: $state})
          }`,
          variables: { state: true } // 必须正确传入此字段
        })
      })
      
    • Apollo Client调用示例:
      import { gql, useMutation } from '@apollo/client';
      
      const ADD_EQUIPMENT = gql`
        mutation MUTATE_AddEquipment($state: Boolean!){
          addEquipment(
            equipment: {
              id: "asd"
              equipmentId: 1
              state: $state
            }
          )
        }
      `;
      
      // 组件内调用
      const [addEquipment] = useMutation(ADD_EQUIPMENT);
      addEquipment({ variables: { state: true } }); // 不可遗漏variables参数
      

额外检查点

  • 排查客户端代码逻辑,确保variables被正确序列化到请求体中
  • 确认state是布尔值类型(true/false),不要传字符串类型的"true"
  • 对照Schema定义,确保变量名称、类型完全匹配(你的Schema中state是必填布尔值Boolean!)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:57:55