1

我有一个组件,我在其中定义了 handleClick (onClick 处理程序),我想调用 Async 函数。下面是我所做的代码,我的问题:为什么在 Async function() 调用中无法访问“this”?

class GameListItem extends BaseComponent {
constructor(props, context) {
    super(props, context);
    this.state = {
        name: props.name,
        owner: props.owner,
        uid: props.uid,
        status: props.status
    };
    this.handleClick = this.handleClick.bind(this);
}

handleClick() {
    let inst = this;
    (
        async function() {

            // WHY HERE 'this' is undefined?

            let res = await inst.engine.async_action({'action': 'join_game', 'data': {'game_uid': inst.state.uid}});
            console.log('res: ', res);
        }()
    );
}

render() {
    return (
        <li className="list-group-item" >
            <ProtectedLink text={this.state.name} classes="game_link" onClick={this.handleClick}/>
        </li>
    );
}
}
4

1 回答 1

0

解决了。我在 IIFE 中失去了上下文。这有效:

    (
        async function(inst) {
            let res = await inst.engine.async_action({'action': 'join_game', 'data': {'game_uid': inst.state.uid}});
            console.log('res: ', res);
        }
    )(this);
于 2017-02-15T06:12:11.423 回答