javascript TypeError:无法读取空的属性“blockNumber”

p8ekf7hl  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(144)

我收到上述错误,代码如下。此错误是否与web3的代码或版本有关?。无法获取交易收据。

try{
        this.setState({blockNumber:"waiting.."});
        this.setState({gasUsed:"waiting..."});

        // get Transaction Receipt in console on click
        // See: https://web3js.readthedocs.io/en/1.0/web3-eth.html#gettransactionreceipt
        await web3.eth.getTransactionReceipt(this.state.transactionHash, (err, txReceipt)=>{
          console.log(err,txReceipt);
          this.setState({txReceipt});
        }); //await for getTransactionReceipt

        await this.setState({blockNumber: this.state.txReceipt.blockNumber});
        await this.setState({gasUsed: this.state.txReceipt.gasUsed});    
      } //try
    catch(error){
        console.log(error);
      } //catch
  } //onClick
vyswwuz2

vyswwuz21#

this.setState是一个异步函数,所以当你从状态this.state.txReceipt得到值时,并不保证它存在。
我会修复你的代码,请告诉它是否工作:

try {
  this.setState({
    blockNumber: "waiting..",
    gasUsed: "waiting.."
  });

  // get Transaction Receipt in console on click
  // See: https://web3js.readthedocs.io/en/1.0/web3-eth.html#gettransactionreceipt
  await web3.eth.getTransactionReceipt(
    this.state.transactionHash,
    (err, txReceipt) => {
      console.log(err, txReceipt);
      if (txReceipt) {
        this.setState({
          blockNumber: txReceipt.blockNumber,
          gasUsed: txReceipt.gasUsed
        });
      }
    }
  ); //await for getTransactionReceipt
} catch (error) {
  //try
  console.log(error);
} //catch

相关问题