使用Apollo-link-state执行Mutation时出现Store写入错误求助
解决Apollo Link State Mutation时的"Cannot read property 'location' of undefined"错误
嘿,我之前也踩过这个坑!这个错误本质是你的mutation resolver在尝试访问location属性时,它的父对象是undefined,大概率是state读取或注入环节出了问题,咱们一步步排查修复:
首先,确认你的Apollo Client初始化时,有没有把默认状态正确注入缓存。很多人容易漏这一步——你定义了defaultState,但必须把它传给InMemoryCache的defaults配置项,不然缓存根本不知道有这个初始值:
import { InMemoryCache } from 'apollo-cache-inmemory'; import defaultState from './your-default-state-path'; const cache = new InMemoryCache({ defaults: defaultState // 这里一定要把默认state传进来! }); // 正常创建Apollo Client const client = new ApolloClient({ link: ApolloLink.from([stateLink, httpLink]), // 确保stateLink是你的apollo-link-state实例 cache });
接下来看mutation resolver的写法,这是最容易出问题的地方。很多人会直接用resolver的第一个参数(root)取state,但某些场景下root可能是undefined,更可靠的方式是通过cache.readQuery主动读取当前客户端状态:
假设你的更新location的mutation resolver应该这么写:
import gql from 'graphql-tag'; import { ApolloLink } from 'apollo-link'; import { withClientState } from 'apollo-link-state'; const resolvers = { Mutation: { updateLocation: (_, { coords }, { cache }) => { // 先读取当前缓存里的location状态 const { location } = cache.readQuery({ query: gql` query getLocation { location @client { coords __typename } } ` }); // 生成新的location对象,保留__typename很重要 const newLocation = { ...location, coords }; // 把新状态写回缓存 cache.writeQuery({ query: gql` query getLocation { location @client { coords __typename } } `, data: { location: newLocation } }); return newLocation; } } }; // 创建stateLink时传入cache、resolvers和默认状态 const stateLink = withClientState({ cache, resolvers, defaults: defaultState // 双重保险,这里也可以传入默认状态 });
另外还要检查你的mutation定义,必须加上@client指令告诉Apollo这是客户端侧的操作:
mutation UpdateLocation($coords: [Float]!) { updateLocation(coords: $coords) @client }
最后再核对几个细节:
- 确保
defaultState里的__typename和查询、resolver里的一致,都是'Location' - 写回缓存时的
data结构必须和readQuery的结构完全匹配,不能少字段 - 尽量不要在resolver里直接用
root.location,因为root参数在apollo-link-state的部分版本里可能不会正确传递当前state
这样调整之后,应该就能解决那个"Cannot read property 'location' of undefined"的错误了!
内容的提问来源于stack exchange,提问作者reggie3
相关产品推荐
相关产品推荐

