繁体   English   中英

可变阶段使返回不确定

[英]Variable stage keeps coming back undefined

嗨,我正在尝试从函数test()获取结果,并使用它来设置变量stageIs但是它总是返回undefined 任何帮助将不胜感激,我已经尝试解决了几个小时。

var stage;
import { CONTRACT } from '../contract'
import _ from 'lodash'

export default {
  data () {
    return {
      stageIs: null,
      amount: null
    }
  },

  mounted () {
    this.coinbase = CONTRACT._eth.coinbase
    this.test()
  },

  methods: {
    test () {
      CONTRACT.name1(function(err, res) {   
        stage = (res);      
      });
      alert(stage);
      this.stageIs= (stage)   
    }

当我在test()执行警报时,它可以工作,但是由于某种原因,它不会设置{{ stageIs }}

test () {
  CONTRACT.name1(function(err, res) {   
    stage = (res);
    alert(stage)
    this.stageIs = (stage)
 })

您有一个匿名函数作为CONTRACT.name1的参数。 通过此匿名函数的签名, name1似乎是异步的。

结果,对name1的调用将立即返回,而应该由name1完成的工作将在事件循环中稍后执行(或正在等待IO)。 结果, stage将始终是不确定的。

您要做的是:

test () {
  let that = this;
  CONTRACT.name1(function(err, res) {   
    stage = (res);
    alert(stage)
    that.stageIs = stage;
  });
}

这里发生两件事。 当异步函数name1调用回调时,我们将为stage分配一个值。 我们还this内部test分配了一个引用,因为匿名函数将在不同的上下文中执行(因此,匿名函数的this会指向其他内容)。

或者,您也可以使用箭头函数摆脱this绑定问题。

test () {
  CONTRACT.name1((err, res) => {   
    stage = (res);
    alert(stage)
    this.stageIs = stage;
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM