15
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactで発生する`Uncaught Invariant Violation: addComponentAsRefTo(...)`エラーの対応策

15
Last updated at Posted at 2015-12-31

つまりはこれ。

Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).

随分はまってしまったので忘れないようにメモとして残しておきます。
結論から言うとwebpackのexternalsで回避しました。

バージョン

モジュール バージョン
React 0.14.5
Webpack 1.7.0
react-bootstrap 0.28.1
redux-devtools-log-monitor 1.0.1

起因

react-bootstrapredux-devtools-log-monitornpm installしてwebpackで依存性を解決した際に突然発生しました。

原因

リンク先のjimfb/react-refs-must-have-owner.mdにある、2. Multiple copies of Reactが理由でした。

詳細

いくつか前提条件があります。

  • 以下のようにwebpackでreactなどライブラリを(開発時のビルド時間短縮などの目的で)vendor.bundle.jsapp.bundle.jsのような形で複数ファイルにビルドしている。

    <html>
      <head>
        <!-- reactやjQueryなどのライブラリを個別にビルドして読み込み -->
        <script src="/dist/vendor.bundle.js"></script>
      </head>
      <body>
        <div id="app"></div>
        <!-- 実際の実装は別にビルドして読み込み -->
        <script src="/dist/app.bundle.js"></script>
      </body>
    </html>
    
  • ライブラリ内部でreactの依存関係をrequireなどで読み込んでいる
    例えばreact-bootstrapのAlertなどは、import React from 'react';などの様に読み込んでいる。

はまった理由

npm ls | grep reactで確認しても複数のreactモジュールを読み込んでいませんでした(だって別に読み込んでいる訳ですし)。

対策

webpackのexternalsを使って、外部モジュールを解決させます。

{
  externals: [
    {
      "react": "React",
      "react-dom": "ReactDOM"
    }
  ]
}

こうするとビルド結果がこんな感じになります。

function(module, exports) {

	module.exports = React;

/***/ }

オチ

内容を整理してこの投稿を書いているときにスレッドを追ってみるとちゃんとコメントされてましたorz...。

以上です。
webpackバンザイ。

15
11
1

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
15
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?