【问题标题】:Accessing props in .then (React/redux)在 .then 中访问 props (React/redux)
【发布时间】:2026-02-01 16:20:06
【问题描述】:

我的项目正在使用 react、redux 和 redux-thunk。

我想在启动清除页面的功能之前等待我的功能结束。不幸的是,我在 .then 中访问我的函数时遇到问题

这是我之前没有承诺的代码,然后:

this.props.dispatch(ScheduleAction(..))
this.props.deleteTab()

问题是有时在将信息发送到我的服务器之前调用 deleteTab() 所以不是很好。

然后我做到了:

Promise.resolve(this.props.dispatch(ScheduleAction(..)))
  .then(function(response) {
         this.props.deleteTab();
         console.log("TabDeleted !!!");
         return response
   })

现在的问题是我无法访问this.props.deleteTab();

我有这个错误:

Uncaught (in promise) TypeError: Cannot read property 'props' of undefined

如果有人知道如何通过访问 .then 中的道具来解决此问题,请提前致谢!!

【问题讨论】:

  • 您是否尝试过在您的promise 之外定义this.props?或者你也可以在你的.then()函数参数中传递this.props作为参数。

标签: javascript reactjs redux promise redux-thunk


【解决方案1】:

这里的问题是您丢失了this 关键字的上下文,这意味着this 现在是未定义的。

由于您可以在 Promise 之外访问 this.props,因此您想要的是在您的 promise 函数中通过这样做来访问 bind this

Promise.resolve(this.props.dispatch(ScheduleAction(..)))
  .bind(this)
  .then(function(response) {
         this.props.deleteTab();
         console.log("TabDeleted !!!");
         return response
   })

【讨论】:

    【解决方案2】:

    试试这个。那时您无法访问此内部。如果你使用如下箭头方法,你应该可以访问它。

    Promise.resolve(this.props.dispatch(ScheduleAction(..)))
      .then((response)=> {
             this.props.deleteTab();
             console.log("TabDeleted !!!");
             return response
       })
    

    【讨论】:

    【解决方案3】:

    希望这个方法对你有用

    const $this = this;
    const { dispatch } = this.props;
    
    Promise.resolve(dispatch(ScheduleAction(..)))
    .then(function(response) {
      $this.deleteTab();
      console.log("TabDeleted !!!");
      return response;
    })
    

    【讨论】: