TypeError: Cannot read property of undefined with web-sockets

TypeError: Cannot read property of undefined with web-sockets

使用 React 和 pusher 的 Isomorphic 框架来获取 websockets。

我在 componentDidMount() 函数中似乎无法访问状态。

class TopbarNotification extends Component {
   state = {
     visible: false,
     notifications: []
   };

  constructor(props) {
    super(props);
    this.state = {
     notifications: [],
     visible: false
    };
  }

  componentDidMount() {
    var pusher = new Pusher('xxxxxxxxxxxx', {
       cluster: 'xxx',
       encrypted: true
    });

    var channel = pusher.subscribe('notifications');
    channel.bind('new-notification', function (data) {
      let newNotifications = this.state.notifications.push(data)
      this.setState({
        notifications: newNotifications
      })
      alert(data.message);
    });

  }

  render() {
     // ...Blah blah, blah blah
  }
}

我收到此错误:TypeError: Cannot read property 'notifications' of undefined

参考这一行:let newNotifications = this.state.notifications.push(data)

为什么我无法访问 componentDidMount() 中的 state

你能测试一下吗:

  componentDidMount() {
    var pusher = new Pusher('xxxxxxxxxxxx', {
      cluster: 'xxx',
      encrypted: true
    });
    let _this = this;

    var channel = pusher.subscribe('notifications');
    channel.bind('new-notification', function (data) {
      let newNotifications = _this.state.notifications.push(data);
      _this.setState({
        notifications: newNotifications
      })
      alert(data.message);
    });

  }

给予 channel.bindfunction 盖过了 componentDidMount()this。使用 arrow function 应该可以解决问题。

channel.bind('new-notification', data => {
  let newNotifications = this.state.notifications.push(data)
  this.setState({
    notifications: newNotifications
  })
  alert(data.message);
});