【问题标题】:got an ''Unexpected strict mode reserved word" when try to use await [duplicate]尝试使用等待时得到“意外的严格模式保留字” [重复]
【发布时间】:2020-11-09 09:07:37
【问题描述】:

这里是代码示例:


class App extends Component {
  constructor() {
    super();
    this.state = {
      currentColor: "red"
    };

    while(1){
   await this.changeColor();
    }
  }

  changeColor = async () => {
    console.log("123")
     setTimeout(() => {
      this.setState({
        currentColor: "yellow"
      });
      setTimeout(() => {
        this.setState({
          currentColor: "green"
        });
        setTimeout(() => {
          this.setState({
            currentColor: "red"
          });
        }, 100);
      }, 200);
    }, 300);
  };

  render() {
    return (
      <div>
        <div
          className={this.state.currentColor}
          style={{ width: "100px", height: "100px" }}
        />
      </div>
    );
  }
}

当我在 changeColor() 前面添加 await 时,出现“意外的严格模式保留字”错误。在线代码:https://stackblitz.com/edit/react-cm4jdq。 (我想纠正一个红绿灯演示)

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您只能在异步函数的上下文中使用 await。构造函数不是异步的,因此是错误的。构造函数不能声明为异步,因为构造函数必须返回构造的对象,并且异步函数返回一个承诺。

    好消息是 changeColor 不需要异步,也不需要在永无止境的 while 循环中等待它。如果您希望它连续运行,请使用setInterval 而不是 setTimeout。

    我还建议您循环浏览一组颜色,而不是为每个颜色重复 setTimeout/setState。

    
    const classnames = ['yellow', 'green', 'red'];
    
    function App () {
      const [colorIndex, setColorIndex] = React.useState(0);
    
      React.useEffect(() => {
        const interval = setInterval(() => {
          this.setState({
            colorIndex: (colorIndex + 1) % colors.length
          }), 100);
        });
    
        // cancel interval on unmount
        return () => clearInterval(interval);
      }, [])
    
      return <div className={classnames[colorIndex]}> ... </div>
    }
    

    【讨论】:

    • 我猜交通信号灯不会在100ms 的相同间隔内在绿色、黄色和红色之间切换。此外,您会立即清除间隔,而不是返回执行此操作的函数。
    • 谢谢,但由于 setTimeout 是异步的。如何结合等待和 setTimeout?我想在 setTimeout 完成后执行下一个循环。
    • 哦,我刚刚发现我可以在innermostTimeout 函数中添加this.changeColor(),而且我认为你的解决方案更优雅。非常感谢
    • setTimeout 并不是你所说的异步。是的,它是异步的,但不是异步/等待意义上的。它不返回一个承诺,你不能等待它。
    • 糟糕。 clearTimeout 调用应该是效果的清理函数,而不是立即调用它。固定。
    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 2017-03-15
    • 1970-01-01
    • 2020-04-28
    • 2018-03-27
    • 2020-05-07
    • 1970-01-01
    • 2015-04-09
    相关资源
    最近更新 更多