You need to enable JavaScript to run this app. Redux Toolkit配置createAsyncThunk显式泛型后upsertMany报类型错误
优惠活动
大模型
产品
解决方案
定价
更多

Redux Toolkit配置createAsyncThunk显式泛型后upsertMany报类型错误

Redux Toolkit 异步Thunk结合Entity Adapter的类型报错问题

在使用Redux Toolkit开发通知模块时,遇到如下类型异常:
传入Notifications类型单值时,notificationsAdapter.upsertMany()抛出类型不匹配错误,提示该类型无法赋值给要求的Notifications[] | Record<EntityId, Notifications>集合类型参数。

触发报错的实现代码

export const fetchNotifications = createAsyncThunk<
  Notifications,
  void,
  { state: RootState }
>("notifications/fetchNotifications", async (_, { getState }) => {
  const allNotifications = selectAllNotifications(getState());
  const [latestNotification] = allNotifications;
  const latestTimestamp = latestNotification ? latestNotification.date : "";
  const response = await client.get(
    `/fakeApi/notifications?since=${latestTimestamp}`
  );
  return response.notifications;
});

const notificationsSlice = createSlice({
  name: "notifications",
  initialState,
  reducers: {
    allNotificationsRead(state) {
      Object.values(state.entities).forEach((notification) => {
        notification && (notification.read = true);
      });
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchNotifications.pending, (state) => {
      state.status = "loading";
    });
    builder.addCase(fetchNotifications.rejected, (state, action) => {
      state.status = "failed";
      state.error = action.error.message as Error;
    });
    builder.addCase(fetchNotifications.fulfilled, (state, action) => {
      state.status = "succeeded";
      Object.values(state.entities).forEach((notification) => {
        notification && (notification.isNew = !notification.read);
      });
      notificationsAdapter.upsertMany(state, action.payload);
    });
  },
});

异常复现的配置细节

  • 代码中为createAsyncThunk显式指定了全量泛型参数,依次为:异步逻辑返回值类型Notifications、thunk入参类型void、自定义ThunkApiConfig配置(其中state字段指定为全局根状态类型RootState,该RootState由store实例自动推导生成,定义格式为export type RootState = ReturnType<typeof store.getState>)
  • 临时规避报错的方案:移除createAsyncThunk上的所有显式泛型标注,在异步逻辑内部手动将getState()的返回值断言为RootState类型时,上述upsertMany的类型报错会完全消失
  • 当前待排查问题:无法定位显式配置的泛型参数中,哪一项导致了fulfilledaction的payload类型推导异常,最终引发Entity Adapter方法的类型匹配错误。

内容的提问来源于stack exchange,提问作者yudhiesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 22:36:07