在 redux 中的自定义中间件中调度异步函数

问题描述

我正在尝试创建一个自定义中间件,它根据 redux 中的某些条件分派 logout 操作(异步函数)。一旦动作被分派,它就会抛出错误 RangeError: Maximum call stack size exceeded

store.js:

const handleAction = (store) => (next) => (action) => {
  const token = loadState(TOKEN);
  const { userAccount } = store.getState();
  if (token && userAccount.email) {
    const decodedJwt = jwt_decode(token);
    if (decodedJwt.exp < dayjs().unix()) {
      store.dispatch(logoutAction());
    }
  }
  return next(action);
};

export function configureStore(initState = {}) {
  const store = createStore(
    rootReducer,initState,composeEnhancers(applyMiddleware(thunk,handleAction))
  );
  return store;
}

我做错了什么?提前致谢

解决方法

防止 logoutAction() 导致中间件分派 logoutAction() 等等...

if(action.type === 'your logoutAction type') return next(action);

示例:

const handleAction = (store) => (next) => (action) => {

  if(action.type === 'your logoutAction type') return next(action);
  
  const token = loadState(TOKEN);
  const { userAccount } = store.getState();
  if (token && userAccount.email) {
    const decodedJwt = jwt_decode(token);
    if (decodedJwt.exp < dayjs().unix()) {
      store.dispatch(logoutAction());
    }
  }
  return next(action);
};

您也可以将其与您现有的条件结合起来:

const handleAction = (store) => (next) => (action) => {     
  const token = loadState(TOKEN);
  const { userAccount } = store.getState();
  if (action.type !== 'your logoutAction type' && 
      token && 
      userAccount.email) {
    const decodedJwt = jwt_decode(token);
    if (decodedJwt.exp < dayjs().unix()) {
      store.dispatch(logoutAction());
    }
  }
  return next(action);
};