Uncaught TypeError: Cannot read property 'showBarChart' of undefined in React

Uncaught TypeError: Cannot read property 'showBarChart' of undefined in React

我有一个自定义 nvd3 scatterChart 绘图的工具提示的功能。在我想更新状态的函数中,我调用了另一个执行 setState:

的函数
chart.tooltip.contentGenerator(function (d) {
      var html = "<div>";
      d.series.forEach(function(elem){
        Object.keys(data_obj).forEach(function(key_1) {
          var outer_obj = data_obj[key_1];
          if (outer_obj["key"] === elem.key) {
             // THIS FUNCTION UPDATES STATE
             this.showBarChart(elem.key);

              var expr = outer_obj["values"][0]["expr"];
              html += "<p>" + elem.key + "</p>";
              html += "<p>x = " + d.value + ", y = " + elem.value + "</p>";
          }
        });
      })
      html += "</div>";
      return html;
    }).bind(this);

在构造函数中我有:

class ScatterChart extends React.Component {
  constructor(props){
  super(props);
  this.createScatterChart = this.createScatterChart.bind(this);
  this.showBarChart = this.showBarChart.bind(this);
  this.state = {
      neuron_name: ""
  }
}

render

render() {
console.log(this.state.neuron_name);
  return <div width={500} height={500}>
          <svg ref={node => this.node = node} width={500} height={500}></svg>
          <BarChart datum = { expressionDatum.getDatumForNeuron(this.state.neuron_name) }/>
        </div>
}

如何让 contentGenerator 函数看到 this 对象?

我能够通过分配 that = this 然后访问 that 来设置状态:

 var that = this;
    chart.tooltip.contentGenerator(function (d) {
      var html = "<div>";
      d.series.forEach(function(elem){
        Object.keys(data_obj).forEach(function(key_1) {
          var outer_obj = data_obj[key_1];
          if (outer_obj["key"] === elem.key) {
              that.showBarChart(elem.key);
              var expr = outer_obj["values"][0]["expr"];
              html += "<p>" + elem.key + "</p>";
              html += "<p>x = " + d.value + ", y = " + elem.value + "</p>";

          }
        });
      })
      html += "</div>";
      return html;
    });

虽然当 nvd3 疯狂地打印 tooltips 时会导致一个奇怪的错误,但我可以更新状态。