Redux-toolkit、RTK Query:使用fixedCacheKey时onCacheEntryAdded不生效?
问题:RTK Query Mutation设置fixedCacheKey后onCacheEntryAdded钩子不触发
我尝试在POST请求成功时执行console.log(),后续还要实现WebSocket订阅或状态更新,但遇到问题:给mutation配置fixedCacheKey后,onCacheEntryAdded钩子完全无法正常工作。相关代码如下:
const [fetchList, list] = rtkApi.useListMutation({ fixedCacheKey: 'FIXED_CACHE_KEY', }); // ... list: builder.mutation({ query: () => ({ method: "POST", url: `/some-url`, }), async onCacheEntryAdded(arg, { cacheDataLoaded, cacheEntryRemoved }) { console.log("log me please"); await cacheDataLoaded; console.log("log again"); }, })
解决方案
1. 为mutation配置keepUnusedDataFor
RTK Query的Mutation默认不会缓存结果,即便设置了fixedCacheKey,如果没有配置缓存保留时间,缓存条目可能不会被持久化,导致onCacheEntryAdded无法触发。添加keepUnusedDataFor来指定缓存保留时长:
list: builder.mutation({ query: () => ({ method: "POST", url: `/some-url`, }), keepUnusedDataFor: 60, // 缓存保留60秒,可按需调整 async onCacheEntryAdded(arg, { cacheDataLoaded, cacheEntryRemoved }) { console.log("log me please"); await cacheDataLoaded; console.log("log again"); // 后续WebSocket订阅逻辑可在此添加 }, })
2. 确保组件中访问了Mutation的缓存数据
RTK Query的缓存是惰性加载的,只有当组件尝试访问Mutation的缓存结果时,才会创建缓存条目并触发onCacheEntryAdded。你需要在组件中使用useListMutation返回的data或相关属性:
const [fetchList, { data, isLoading }] = rtkApi.useListMutation({ fixedCacheKey: 'FIXED_CACHE_KEY', }); // 示例:访问data以触发缓存加载 if (data) { console.log('Mutation返回结果:', data); }
3. 添加错误捕获排查问题
onCacheEntryAdded是异步函数,若内部出现未捕获的错误,会导致钩子静默失败。添加try/catch来排查潜在错误:
async onCacheEntryAdded(arg, { cacheDataLoaded, cacheEntryRemoved }) { try { console.log("log me please"); await cacheDataLoaded; console.log("log again"); // WebSocket订阅逻辑 } catch (error) { console.error('onCacheEntryAdded执行出错:', error); } }
内容的提问来源于stack exchange,提问作者Vitaliy D
相关产品推荐
相关产品推荐

