8
7

More than 5 years have passed since last update.

bindした関数は別のオブジェクトになる

Posted at

このコードを見て「そりゃあそうだろ」と思う方は読む価値はございません。

    var func = function(){};
    console.log(func === func);//true
    console.log(func.bind(this) === func.bind(this));//false

(とりあえずChromeのみで確認してます)

事の発端はReact+Flux+ES6でとあるアプリを開発中、下記のウォーニングに見舞われデバッグで手間取りました。

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

読んだ通りの内容で、マウントされていないComponentにsetStateを呼ぶと出るウォーニングですが、どこをどう見てもマウントしてるんですね。で、デバッガーやらconsole.logなんかを駆使して、やっと気づいたのですが、UnmountしたComponentのイベントが削除されていなかったのが原因でした。

問題のあるComponentのイベント登録部分の実装です。

export default class BaseComponent extends React.Component
{
  constructor(props) {
    super(props);
    this.store = this.initStore();
    this.state = this.store.getInitialState();
  }

  initStore(){
    throw 'You must implements initStore().';
  }

  onStoreChange(callback){
    this.setState(this.store.getUpdatedState(), callback);
  }

  componentWillMount() {
    this.store.addChangeListener(this.onStoreChange.bind(this));
  }

  componentWillUnmount() {
    this.store.removeChangeListener(this.onStoreChange.bind(this));
  }
}

this.storeの各メソッドは下記の通り(一部抜粋)。

export default class BaseStore extends Events.EventEmitter
{
  //...

  addChangeListener(callback) {
    this.on('change', callback);
  }

  removeChangeListener(callback) {
    this.removeListener('change', callback);
  }
}

callback === callbackfalseなんで破棄されてなかったんですね。いろんな方法があると思いますが、とりあえず下記のようにして対応しました。

export default class BaseComponent extends React.Component
{
  constructor(props) {
    super(props);
    this.store = this.initStore();
    this.state = this.store.getInitialState();

    this.storeChangeCallback = (callback) => {
      this.setState(this.store.getUpdatedState(), callback);
    };
  }

  initStore(){
    throw 'You must implements initStore().';
  }

  componentWillMount() {
    this.store.addChangeListener(this.storeChangeCallback);
  }

  componentWillUnmount() {
    this.store.removeChangeListener(this.storeChangeCallback);
  }
}

ちなみにes6の() => {}内のthisは外スコープのthisになります(Babelを使用してます)。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7