Redux Toolkit组合多中间件时toastMiddleware重复执行问题求助
Redux Toolkit 组合中间件导致Toast重复触发问题解决
你的问题出在combinedMiddleware的写法不符合Redux中间件的链式调用规范,导致action被重复处理,最终触发两次toast提示。
问题根源
你当前的combinedMiddleware直接返回了两个中间件执行结果的数组,相当于让两个中间件并行处理同一个action,并且都调用了next(action),导致action被两次传递到后续流程。虽然console.log只执行一次(因为action只进入toastMiddleware一次),但两次next(action)会让整个中间件链重复处理action,最终导致addToast被dispatch两次。
修复方案
需要将两个中间件链式串联,让action依次经过apiErrorMiddleware、toastMiddleware,最后传递给后续中间件或store。修改middleware.js中的combinedMiddleware:
import { addError } from "../error.slice"; import { addToast } from "../toast.slice "; const apiErrorMiddleware = (api) => (next) => (action) => { if (action.type.endsWith('/rejected') && action.payload && action?.payload?.status != 401) { api.dispatch(addError({ response: action.payload, meta: action.meta, arg: action.error })); } return next(action); }; const toastMiddleware = (api) => (next) => (action) => { const mutationVerb = action?.payload?.created?.length ? 'Created' : action?.payload?.updated?.length ? 'Updated' : action?.payload?.upserted?.length ? 'Upserted' : null; if (action.type.endsWith('executeMutation/fulfilled')) { console.log('toast mid', action) if (mutationVerb) api.dispatch(addToast({title: mutationVerb, content: 'Operation completed successfully.', variant: 'success'})); else api.dispatch(addToast({title: 'No Change', content: 'Operation completed successfully.', variant: 'info'})); } return next(action); }; // 正确的链式组合方式 export const combinedMiddleware = (api) => (next) => (action) => { // 让action先经过apiErrorMiddleware,再传递给toastMiddleware,最后到原next return apiErrorMiddleware(api)(toastMiddleware(api)(next))(action); };
代码说明
- 这里通过嵌套调用,把
toastMiddleware作为apiErrorMiddleware的next函数,实现了中间件的链式处理。 - 当action进入时,会先被
apiErrorMiddleware处理,然后传递给toastMiddleware,最后再传递给后续的中间件或store,确保每个action只被完整处理一次。
修改后,你的store.js不需要改动,保持原配置即可。此时toast提示只会触发一次,console.log也会正常输出一次。
内容的提问来源于stack exchange,提问作者David Johns
相关产品推荐
相关产品推荐

