RTK Query中如何通过useEffect更新state及ConditionError报错解决
错误原因
这个ConditionError是Redux Toolkit Query(RTKQ)内置的请求中止错误,触发原因如下:
- 默认情况下
endpoint.initiate()方法会先执行内置的条件检查:如果相同参数的请求已经在进行中、或者对应接口的缓存仍在有效期内,条件回调会返回false,直接中止新请求,抛出该错误。 - 你的代码里依赖
success(添加评论成功的状态)触发useEffect重新执行,每次添加评论完成后都会重复调用getPost.initiate(id),此时如果getPost的缓存未过期,就会命中中止逻辑。 - 额外排查点:如果你为
getPost接口自定义了condition回调,也可能是回调逻辑返回false主动中止了请求。
解决方案
有两种常用修复方案,优先选择第一种官方推荐方案:
方案1:使用RTKQ标签自动失效机制(推荐)
不需要手动写useEffect触发刷新,通过标签关联两个接口的依赖关系,添加评论成功后自动触发getPost接口刷新:
- 调整
postApi的定义,给两个接口添加关联标签:
export const postApi = createApi({ reducerPath: 'postApi', baseQuery: fetchBaseQuery({ baseUrl: '/api' }), tagTypes: ['Post'], // 声明标签类型 endpoints: (builder) => ({ getPost: builder.query({ query: (id) => `/posts/${id}`, // 给返回的Post数据打标签 providesTags: (result, error, id) => [{ type: 'Post', id }], }), addNewComment: builder.mutation({ query: (commentData) => ({ url: '/comments', method: 'POST', body: commentData, }), // 评论提交成功后,失效对应Post的缓存,自动触发重新请求 invalidatesTags: (result, error, commentData) => [{ type: 'Post', id: commentData.postId }], }), }), })
- 简化组件代码,直接使用自动生成的Query Hook,不需要手动调度请求:
const PostDetails = (props) => { const id = props.match.params.id; const [addNewComment, { isSuccess: success, isError }] = useAddNewCommentMutation(); // 直接使用内置Hook,缓存失效后会自动刷新数据 const { data: post, isLoading } = useGetPostQuery(id); // 剩余业务逻辑... }
方案2:强制跳过条件检查
如果需要保留手动调用initiate的逻辑,可以添加forceRefetch参数跳过缓存和请求状态检查,强制发起新请求:
useEffect(() => { // 新增forceRefetch配置 const result = dispatch(postApi.endpoints.getPost.initiate(id, { forceRefetch: true })); return result.unsubscribe; }, [id, dispatch, success]);
内容的提问来源于stack exchange,提问作者en nice
相关产品推荐
相关产品推荐

