在 mutation 中实现点赞 +1 的乐观更新。

解读

国内面试官问“在 mutation 中实现点赞 +1 的乐观更新”,并不是让你真的去 Redux 里直接修改 state,而是考察三件事:

  1. 是否理解 Redux 要求不可变更新 这一铁律;
  2. 是否能在 RTK Query 的 mutation 生命周期 里做乐观更新,即先写后校验;
  3. 能否处理 失败回滚、并发冲突、幂等性 这些线上真实场景。
    答题时必须明确:乐观更新≠直接改 state,而是利用 onQueryStarted 的 patchQueryData 实现“假写”,并在 queryFulfilled 或 queryRejected 里做提交或回滚。

知识点

  • RTK Query 的 mutation 生命周期:onQueryStarted → 网络请求 → queryFulfilled / queryRejected
  • 乐观更新 API:dispatch(patchQueryData(getPostById, cacheKey, updater))
  • 不可变更新原则:即使“假写”也要用 Immer 包装,禁止 state.likes++
  • 回滚机制:patchQueryData 返回的 undo 函数必须在 catch 里调用
  • 并发与幂等:同一用户快速点击两次,需用 requestId 或后端唯一索引去重,防止脏写
  • 国内工程规范:乐观更新必须打埋点(如阿里、字节要求的上报 optimistic: true),方便灰度观测

答案

// postSlice.ts
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { RootState } from '../store';

interface Post {
  id: string;
  likes: number;
}

export const postApi = createApi({
  reducerPath: 'postApi',
  baseQuery: fetchBaseQuery({
    baseUrl: '/api',
    prepareHeaders: (headers, { getState }) => {
      const token = (getState() as RootState).user.token;
      if (token) headers.set('authorization', `Bearer ${token}`);
      return headers;
    },
  }),
  tagTypes: ['Post'],
  endpoints: (builder) => ({
    getPostById: builder.query<Post, string>({
      query: (id) => `posts/${id}`,
      providesTags: (res, err, id) => [{ type: 'Post', id }],
    }),
    likePost: builder.mutation<{ likes: number }, string>({
      query: (id) => ({
        url: `posts/${id}/like`,
        method: 'POST',
      }),
      // 关键:乐观更新
      async onQueryStarted(id, { dispatch, queryFulfilled }) {
        // 1. 假写:立即把 likes +1
        const patchResult = dispatch(
          postApi.util.updateQueryData('getPostById', id, (draft) => {
            draft.likes += 1;
          })
        );
        // 2. 埋点:国内大厂要求
        window.goldlog?.emit('optimistic_like', { postId: id, action: 'optimistic' });
        try {
          // 3. 等待真实接口返回
          const { data } = await queryFulfilled;
          // 4. 提交:后端返回最新值,缓存自动覆盖
          window.goldlog?.emit('optimistic_like', { postId: id, action: 'committed' });
        } catch (err) {
          // 5. 回滚:网络失败或业务码异常
          patchResult.undo();
          window.goldlog?.emit('optimistic_like', { postId: id, action: 'rollback' });
          // 6. 用户提示
          antd.message.error('点赞失败,请重试');
        }
      },
      invalidatesTags: (res, err, id) => [{ type: 'Post', id }],
    }),
  }),
});

export const { useGetPostByIdQuery, useLikePostMutation } = postApi;

使用侧(React 组件)完全无感知:

const [likePost] = useLikePostMutation();
<button onClick={() => likePost(postId)}>👍</button>

拓展思考

  1. 双端一致性:国内 App 常同账号多端登录,乐观值需与长连接(WebSocket)推送做冲突合并,可用向量时钟或时间戳对齐。
  2. 限流防抖:点赞按钮 300 ms 防抖,并在 onQueryStarted 里用 requestId 去重,防止用户狂点造成雪崩。
  3. 灰度开关:通过配置中心(如阿里 Diamond、字节 FeatureCenter)下发 optimisticLike=false,可在事故时秒级关闭乐观更新。
  4. 安全合规:网信办要求用户行为可溯源,乐观更新日志必须带上 userId+deviceId,保存 180 天备查。