我有一个组件,我定义了handleClick(onClick处理程序),我想调用Async函数。代码低于我所做的,我的问题:为什么'this'在Async function()调用中无法访问?
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>
);
}
}
答案 0 :(得分: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);