You need to enable JavaScript to run this app. 如何在redux-toolkit的slice中捕获所有pending和rejected类型的action?
优惠活动
大模型
产品
解决方案
定价
更多

如何在redux-toolkit的slice中捕获所有pending和rejected类型的action?

可行实现方案(基于Redux Toolkit原生能力,无需额外中间件)

Redux Toolkit的extraReducers支持addMatcher方法,允许你通过自定义规则匹配批量action,完全可以实现全局/指定范围的pending状态监听,不需要逐个添加每个异步thunk的pending case。

方案1:匹配所有异步thunk的pending action

如果你要捕获全局所有由createAsyncThunk生成的pending状态action,直接用RTK内置的isPending匹配器即可:

import { createSlice, isPending, isFulfilled, isRejected } from '@reduxjs/toolkit'

const uiSlice = createSlice({
  name: 'ui',
  initialState: {
    loading: false,
    loadingCount: 0 // 用于处理多请求并行场景,避免提前关闭加载框
  },
  reducers: {},
  extraReducers: (builder) => {
    // 所有pending动作触发时执行
    builder.addMatcher(isPending, (state) => {
      state.loadingCount += 1
      state.loading = true
    })

    // 所有成功/失败动作触发时执行
    builder.addMatcher(
      (action) => isFulfilled(action) || isRejected(action),
      (state) => {
        state.loadingCount -= 1
        if (state.loadingCount === 0) {
          state.loading = false
        }
      }
    )
  }
})

方案2:仅匹配当前slice内的所有pending action

如果你不想受其他slice异步动作的影响,只需要捕获当前slice下的所有pending action,可以自定义匹配规则:

const userSlice = createSlice({
  name: 'user', // 你的slice名称
  initialState: {
    loading: false,
    loadingCount: 0,
    list: []
  },
  reducers: {},
  extraReducers: (builder) => {
    // 仅匹配当前user slice下的pending动作
    builder.addMatcher(
      (action) => action.type.startsWith('user/') && action.type.endsWith('/pending'),
      (state) => {
        state.loadingCount += 1
        state.loading = true
      }
    )

    // 仅匹配当前user slice下的成功/失败动作
    builder.addMatcher(
      (action) => action.type.startsWith('user/') && 
        (action.type.endsWith('/fulfilled') || action.type.endsWith('/rejected')),
      (state) => {
        state.loadingCount -= 1
        if (state.loadingCount === 0) {
          state.loading = false
        }
      }
    )

    // 你原本的其他业务逻辑case可以继续正常加
    // builder.addCase(fetchUsers.fulfilled, (state, action) => {
    //   state.list = action.payload
    // })
  }
})

注意事项

如果你的业务存在并行发起多个异步请求的场景,不要直接在单个请求结束时就把loading状态设为false,通过loading计数器的方式可以避免加载框提前关闭的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 16:24:03