使用apollo-link-state的@client mutation返回空data问题求助
解决Apollo Link State客户端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; }
额外排查建议
- 确认product字段完整性:在Resolver里加个
console.log(product),看看它是不是包含你在Mutation里请求的所有字段(__typename、id、addedToCart等),如果缺字段,返回的data里对应字段会是null。 - 验证缓存更新:在
cache.writeQuery之后,再用cache.readQuery读一次缓存,确认inventory数组确实更新了——这能排除缓存操作的问题。
这样修改后,你调用Mutation时,then里的e.data.updateInventoryItem就会是你期望的product对象了。
内容的提问来源于stack exchange,提问作者Mcbeer
相关产品推荐
相关产品推荐

