React-Redux:无法读取未定义的 属性 'closed'

React-Redux: Cannot read property 'closed' of undefined

在将 dispatch() 与 React-Redux 一起使用时,我似乎遇到了 运行 的问题。例如,以下操作:

export const fetchMetrics = () => {
    dispatch(fetchMetricsBegin);

    APIService.get('/dashboard/info/')
        .then((response) => { 
            dispatch(fetchMetricsSuccess(response));
            return response;
        })
        .catch(error => dispatch(fetchMetricsFailure(error)));
};

产生以下错误:

TypeError: Cannot read property 'closed' of undefined
dispatch
src/internal/observable/pairs.ts:82

这是我的 package.json:

{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@popperjs/core": "^2.6.0",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.6.0",
    "axios": "^0.21.0",
    "dotenv": "^8.2.0",
    "jwt-decode": "^3.1.2",
    "react": "^17.0.1",
    "react-datepicker": "^3.3.0",
    "react-dom": "^17.0.1",
    "react-images-upload": "^1.2.8",
    "react-number-format": "^4.4.1",
    "react-popper": "^2.2.4",
    "react-redux": "^7.2.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.1",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0",
    "rxjs": "^6.6.3",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

我已尝试清除 node_modulepackage-lock.json,但问题仍然存在。欢迎任何见解。删除 dispatch 调用会删除错误。

您正在使用 redux-thunk。该库将允许您执行异步调用,因为您的函数 return 是另一个以 dispatch 作为参数的函数。否则 thunk 将执行代码同步。

export const fetchMetrics = () => (dispatch) => {
    dispatch(fetchMetricsBegin);

    APIService.get('/dashboard/info/')
        .then((response) => { 
            dispatch(fetchMetricsSuccess(response));
            return response;
        })
        .catch(error => dispatch(fetchMetricsFailure(error)));
};