首页 > 解决方案 > 我在 JScript 上遇到未经处理的拒绝错误

问题描述

这是一个去中心化存储网络的 github 脚本,但是每当我上传时,我在 await() 函数中都会收到这个 Unhandled Rejection 错误。

handleSubmit = async (e) => {
    e.preventDefault();
    if (this.state.file !== "") {
        this.setState({ loading: true });
        await this.state.files.add(this.state.file,this.state.file.name);
        this.setState({ loading: false });
        this.getALLHashes();
    }
    else {
        this.setState({ fieldReq: true })
    }
}

我是 JavaScript 新手,所以我不知道如何解决这个问题。请帮忙!!

标签: javascriptasync-await

解决方案


这意味着,如果发生错误,您将没有任何机制来处理该拒绝。使用try / catch. 像这样试试

handleSubmit = async e => {
  e.preventDefault();
  if (this.state.file !== "") {
    try {
      this.setState({ loading: true });
      await this.state.files.add(this.state.file, this.state.file.name);
      this.setState({ loading: false });
      this.getALLHashes();
    } catch (err) {
      console.log(err);
    }
  } else {
    this.setState({ fieldReq: true });
  }
};

推荐阅读