【问题标题】:Error Possible Unhandle promise rejection (React and Class) [duplicate]错误可能未处理的承诺拒绝(反应和类)[重复]
【发布时间】:2021-05-26 18:36:47
【问题描述】:

我希望在一个类中使用一个承诺,并取决于解决或拒绝是否执行我的组件类的另一个方法。 在这里我留下一个代码。

var promise = new Promise( (resolve, reject) => {

  let name = 'DaveA'

  if (name === 'Dave') {
     resolve("Promise resolved successfully");
  }
  else {
     reject(Error("Promise rejected"));
  }
});

class App extends React.Component
{
  constructor(props){
    super(props);
    this.state = {
      name: '',
    }
   
  }
  Bien(result){
    alert("OK")
    this.setState({name: result});
  }
  Mal(error){
    alert("FALLO")
    this.setState({name: error});
  }
  componentDidMount() {
  
 
    let obj = {newName: ''};
   
    promise.then( result => {
     this.Bien(result)
  
    }, function(error) {
      this.Mal(error)
  
    });

我创建了一个简单的承诺。 从 ComponentDidMount 我调用它。 在我调用另一种方法之后。 但从不调用它。 出现错误:

 WARN     Possible Unhandled Promise Rejection (id: 0):
TypeError: this.Mal is not a function. (In 'this.Mal(error)', 'this.Mal' is undefined)

【问题讨论】:

  • 在构造函数中添加 this.Mal = this.Mal.bind(this)
  • 删除 function(error) {...} 部分并在 promise.then() 的末尾添加 .catch()。请检查以下答案。

标签: javascript reactjs react-native promise callback


【解决方案1】:

请使用.catch()

componentDidMount() {
    let obj = {newName: ''};
    promise.then(result => {
     this.Bien(result)
    })
    .catch((error) => {
      this.Mal(error)
    });
  }

所以总代码应该如下:

import React, { Component } from 'react';

var promise = new Promise((resolve, reject) => {
    let name = 'DaveA'
    if (name === 'Dave') {
      resolve("Promise resolved successfully");
    }
    else {
      reject(Error("Promise rejected"));
    }
  });

class App extends React.Component
{
  constructor(props){
    super(props);
    this.state = {
      name: '',
    }
  }

  Bien(result) {
    alert("OK")
    this.setState({name: result});
  }

  Mal(error) {
    alert("FALLO")
    this.setState({name: error});
  }

  componentDidMount() {
    let obj = {newName: ''};
    promise.then(result => {
     this.Bien(result)
    })
    .catch(error => {
      this.Mal(error)
    });
  }

  render() {
    return <></>
  }
}

export default App;

它在“react”:“16.12.0”上正常工作。结果提示“FALLO”。

【讨论】:

  • 不,不要使用catchUsing .then(…, …) is totally fine,尤其是在 OP 的情况下。
  • 没有catch就无法使用
  • 当然可以。注意catch 只是另一个then 调用的别名,处理程序作为第二个参数。
猜你喜欢
  • 1970-01-01
  • 2016-11-24
  • 2020-04-03
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
  • 2016-12-15
  • 2023-01-04
相关资源
最近更新 更多