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

Apollo Client调用Hygraph Mutation报400错误排查求助

排查Apollo Client提交Hygraph Mutation返回400错误的问题

核心问题:变量类型不匹配

你在Hygraph Playground能正常执行Mutation,但代码调用失败,最关键的原因是表单输入值的类型和Mutation定义的类型不匹配:

  • Mutation里count是Int!类型,length是Float!类型,width是可选Float类型
  • 但表单输入的e.target.value默认是字符串类型,直接传递会导致Hygraph接收到错误类型的变量,触发400参数错误

具体修复步骤

1. 修正输入值的类型转换

在表单输入的onChange事件中,把字符串转换为对应的数据类型:

  • 整数类型(count)转成Number
  • 浮点类型(width/length)转成parseFloat,空值时设为null(适配可选参数width)

修改后的表单输入代码:

<label>Name:
  <input
    type="text" 
    value={name}
    onChange={(e) => setName(e.target.value.trim())}
  />
</label>

<label>Count:
  <input
    type="number" 
    value={count}
    onChange={(e) => setCount(e.target.value ? Number(e.target.value) : 0)} // 转成Int,空值设默认0或按需调整
  />
</label>  

<label>Width:
  <input
    type="text" 
    value={width || ''}
    onChange={(e) => setWidth(e.target.value ? parseFloat(e.target.value) : null)} // 空值传null适配可选参数
  />
</label>

<label>Height:
  <input
    type="text" 
    value={length || ''}
    onChange={(e) => setLength(e.target.value ? parseFloat(e.target.value) : 0)} // length为必填,空值设默认或做校验
  />
</label>

2. 增加提交前必填校验

因为name、count、length是必填字段,提交前做简单校验,避免传递无效空值:

<form onSubmit={e => {
  e.preventDefault();
  // 校验必填字段
  if (!name.trim() || isNaN(count) || isNaN(length)) {
    alert('请正确填写所有必填字段');
    return;
  }
  console.log('submitting' , name , count , width , length);
  createInventoryMutation({ variables: { name, count, width, length } });
}}>

3. 查看详细错误信息

如果修复后仍报错,打印完整的error对象,Hygraph会返回具体的字段错误提示,方便定位问题:

if (error) {
  console.error('完整错误详情:', error);
  return `提交错误!${error.message}`;
}

额外提示

  • 注意width是可选参数,若用户未输入,必须传递null而非空字符串,Hygraph才能正确识别
  • 即使是type="number"的输入框,e.target.value依然是字符串类型,必须手动转换为数字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 23:31:21