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

使用apollo-link-state的@client mutation返回空data问题求助

我刚看完你的代码,问题其实出在Resolver的返回格式上——你把Apollo期望的返回结构搞反了!

核心问题:Resolver不需要包装{data: ...}

你的Mutation定义里,updateInventoryItem字段返回的是InventoryItem类型(也就是你请求的__typename、id这些字段对应的对象),所以Resolver应该直接返回这个类型的对象本身,而不是把它包在{data: ...}里。

Apollo Link State会自动把Resolver的返回值作为Mutation字段的结果,最终封装到你看到的data对象里。如果你返回{data: product},那最终data.updateInventoryItem就会是这个带data属性的对象,而不是你要的product——这就导致你请求的id、__typename等字段找不到,所以返回的data看起来是空的。

修正后的Resolver代码

把Resolver的返回改成直接返回product就行:

export const updateInventoryItem = async (product, cache) => {
  const query = gql`query { inventory @client { ...omitted, but all the values } }`;
  const prevState = await cache.readQuery({ query });
  const prevInventory = prevState.inventory;
  const productIndex = prevInventory.findIndex(x => x.id === product.id);
  prevInventory.splice(productIndex, 1);
  const data = { inventory: [ product, ...prevInventory ] }
  await cache.writeQuery({ query, data });
  
  // 直接返回product,匹配Mutation定义的返回类型
  return product;
}

额外排查建议

  1. 确认product字段完整性:在Resolver里加个console.log(product),看看它是不是包含你在Mutation里请求的所有字段(__typename、id、addedToCart等),如果缺字段,返回的data里对应字段会是null。
  2. 验证缓存更新:在cache.writeQuery之后,再用cache.readQuery读一次缓存,确认inventory数组确实更新了——这能排除缓存操作的问题。

这样修改后,你调用Mutation时,then里的e.data.updateInventoryItem就会是你期望的product对象了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:37:12