【问题标题】:React-Redux: Cannot read property 'closed' of undefinedReact-Redux:无法读取未定义的属性“关闭”
【发布时间】:2021-03-28 15:08:39
【问题描述】:

在将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:无法读取未定义的“已关闭”属性
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 调用会删除错误。

【问题讨论】:

  • 不应该是:dispatch(fetchMetricsBegin()); 假设 fetchMetricsBegin 是一个动作创建者函数。该错误看起来并不在您发布的代码中,通常在浏览器内容中是有关错误发生位置的一些信息。

标签: reactjs typescript redux react-redux redux-thunk


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 2019-02-15
    • 1970-01-01
    • 2017-06-22
    • 2021-01-15
    • 2017-09-05
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多