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

dispatch async function in custom middleware in 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);
};