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

React Apollo Mutation组件update函数变量访问及data为空问题排查

解决React Apollo Mutation组件update函数中data为空及访问变量的问题

我来帮你搞定这个问题~你遇到的update函数里data为空的情况,其实是本地@client mutation的常见坑,咱们一步步拆解原因和解决方案:

为什么你的data是空对象?

带@client的本地mutation和远程服务器mutation不一样:远程mutation的data会自动填充服务器返回的结果,但本地mutation的返回值完全由你定义的resolver决定。如果你的resolver没有返回和mutation GraphQL定义匹配的结构,Apollo Client就会返回空的data对象。

解决方案一:让本地mutation返回正确数据

你需要在Apollo Client的resolvers里为这个mutation定义返回值,确保结构和你的GraphQL mutation定义一致(还要包含__typename,Apollo依赖这个识别数据类型)。

举个例子:

// 定义本地mutation的resolver
const resolvers = {
  Mutation: {
    someMutation: (_, { toggleProp }, { cache }) => {
      // 这里先做你需要的缓存更新操作(比如读取现有数据、修改后写回)
      // const currentData = cache.readQuery({ query: YOUR_CACHE_QUERY });
      
      // 关键:返回和mutation定义匹配的结构
      const mutationResult = {
        someProp: {
          toggleProp,
          __typename: 'SomeProp' // 要和你在GraphQL schema里定义的类型名一致
        },
        __typename: 'Mutation'
      };
      
      // 写回缓存(根据你的业务需求调整)
      // cache.writeQuery({
      //   query: YOUR_CACHE_QUERY,
      //   data: { ...currentData, someProp: { toggleProp } }
      // });
      
      return mutationResult;
    }
  }
};

// 把resolvers传给你的ApolloClient实例
const client = new ApolloClient({
  cache: new InMemoryCache(),
  resolvers,
  // 其他配置...
});

这样修改后,update函数里的data就会包含你返回的toggleProp了。

解决方案二:直接在update里访问mutation变量

其实还有更简单的方式——你根本不需要依赖data参数!update函数的第二个参数是一个包含variables的对象,你可以直接解构出调用mutation时传入的变量:

<Mutation 
  mutation={SOME_MUTATION} 
  update={(cache, { variables }) => {
    // 直接拿到你传入的toggleProp!
    console.log(variables.toggleProp); // 输出 true
    
    // 接下来用这个变量更新缓存即可
    const existingCacheData = cache.readQuery({ 
      // 替换成你读取缓存的查询
      query: gql`query GetSomeProp { someProp { toggleProp } }` 
    });
    
    cache.writeQuery({
      query: gql`query GetSomeProp { someProp { toggleProp } }`,
      data: {
        ...existingCacheData,
        someProp: { toggleProp: variables.toggleProp, __typename: 'SomeProp' }
      }
    });
  }}
>
{someMutation => (
  <SomeComponent onClick={() => someMutation({ variables: { toggleProp: true } })} />
)}
</Mutation>

这个方法更直接,尤其适合你只是需要用传入的变量更新缓存的场景,完全不用纠结data为空的问题。

内容的提问来源于stack exchange,提问作者s.brauns

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:28:00