账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    thunk一个异步action调用另一个异步action错误,提示缺少中间件
    • 2018-10-19 00:00
    • 10
    40
    0

    原来这么用是没有问题的,自从更新了create-react-app重新eject与更新了一些依赖库就出现了问题

    1. store

    export const history = createHashHistory({
      basename: '',
      hashType: 'slash',
    });
    
    const initialState = {};
    const enhancers = [];
    const middleware = [
      thunk,
      routerMiddleware(history),
    ];
    
    if (process.env.NODE_ENV === 'development') {
      const devToolsExtension = window.devToolsExtension;
    
      if (typeof devToolsExtension === 'function') {
        enhancers.push(devToolsExtension());
      }
    }
    
    const composedEnhancers = compose(
      applyMiddleware(...middleware),
      ...enhancers,
    );
    
    const store = createStore(
      rootReducer,
      initialState,
      composedEnhancers,
    );
    
    export default store;

    2. action

    export const FETCH_EXPORT_STAGE = 'FETCH_EXPORT_STAGE'
    
    const makeActionCreator = (type, ...argNames) => (...args) => {
      const action = { type };
      argNames.forEach((arg, index) => {
        action[argNames[index]] = args[index];
      });
      return action;
    };
    
    export const pushExportStage = makeActionCreator(FETCH_EXPORT_STAGE, 'payload')
    
    export const fetchExportStage = () => async (dispatch) => {
      const stages = await fetch('/api/findSchoolType')
      dispatch(pushExportStage(stages))
      return stages
    }

    3.component

    componentDidMount () {
        this.props.fetchExportStage()
          .then(stages => {
            if (!stages.length) return
            const defaultStageId = stages[0].id
            this.props.fetchExportSchoolByStage(defaultStageId).then(schools => {
              this.setState({schools})
            })
            this.props.fetchExportIndicatorByStage(defaultStageId).then(indicators => {
              this.setState({indicators})
            })
          });
      }

    报错信息

    ×
    Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.
    ▶ 6 stack frames were collapsed.
    (anonymous function)
    src/routes/home/components/index.js:48
      45 | .then(stages => {
      46 |   if (!stages.length) return
      47 |   const defaultStageId = stages[0].id
    > 48 |   this.props.fetchExportSchoolByStage(defaultStageId).then(schools => {
      49 |  ^  this.setState({schools})
      50 |   })
      51 |   this.props.fetchExportIndicatorByStage(defaultStageId).then(indicators => {

    package.json

    "react": "^16.5.2",
    "react-redux": "^5.0.7",
    "react-redux-loading-bar": "^4.0.8",
    "react-router-dom": "^4.3.1",
    "react-router-redux": "^5.0.0-alpha.9",
    "redux": "^4.0.1",
    "redux-thunk": "^2.3.0",
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • 残あ梦ぎ鱼 普通会员 1楼

      在Redux中,当你尝试在一个异步action creator中调用另一个异步action时,如果遇到“缺少中间件”的错误提示,这通常意味着你没有正确地应用Redux Thunk或其他支持处理异步逻辑的中间件。

      Redux Thunk是一个Redux中间件,它允许你的action creator返回一个函数而不是一个动作对象。这个返回的函数可以延迟dispatch动作,甚至 dispatch多个动作,这对于处理复杂的异步逻辑非常有用。

      例如:

      ```javascript import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers';

      const store = createStore( rootReducer, applyMiddleware(thunk) // 这里是添加Redux Thunk中间件的关键步骤 );

      // 然后你可以定义异步action creator function fetchUser(id) { return function (dispatch) { dispatch({ type: 'FETCH_USER_REQUEST' });

      return fetch(`/api/users/${id}`).then(response =>
        response.json().then(user => {
          dispatch({ type: 'FETCH_USER_SUCCESS', user });
        })
      ).catch(error => {
        dispatch({ type: 'FETCH_USER_FAILURE', error });
      });
      

      }; }

      // 在另一个异步action creator中调用它 function doSomethingAsync() { return function (dispatch, getState) { dispatch(fetchUser(123)); // 调用异步action // ... } } ```

      如果你在尝试上述操作时遇到“缺少中间件”的错误,检查你的store配置,确保已正确安装并应用了Redux Thunk中间件。

    • 血·魅 普通会员 2楼
      { "error": "Failed to generate content." }
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部