Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 15.0.1 Updates causing issues with DOM #6472

Closed
jbbae opened this issue Apr 10, 2016 · 61 comments
Closed

React 15.0.1 Updates causing issues with DOM #6472

jbbae opened this issue Apr 10, 2016 · 61 comments

Comments

@jbbae
Copy link

jbbae commented Apr 10, 2016

Hey,
So I'm a fairly new developer who had a working app until version v0.14.8, and just updated to v15.0.1 today. The update did remove a few errors/warnings I was struggling with (so a great relief there), but brought up this issue.

Specifically, the app itself renders fine, with all the pages looking fine (all components, text, etc. in the right places), but is just "frozen" - completely non-functional, not allowing me to click on anything etc.

The error message I see are as follows (from Chrome and Firefox):
capture
capture2

I back-tracked it to where I could and found this being the part where the "node" is coming off as null:
capture3

So I have absolutely no clue what's going on and there seems to be no hint as to what exactly is causing this issue. I will try ripping the app apart and do a thorough debugging, but wouldn't expect much from it (due to my unfamiliarity with development yet...).
I really really appreciate the help in advance, and hope that this problem can contribute somewhat to improving the React ecosystem!

@roganov
Copy link

roganov commented Apr 10, 2016

React 0.14 warns about deprecations that are removed/changed in React 15. I would suggest to resolve all the errors/warning in 0.14 and then upgrade.

@gaearon
Copy link
Collaborator

gaearon commented Apr 10, 2016

Please make sure you don’t have two instances of React on the same page.
npm ls react can help to determine this.

If you don’t, please share the minimal example reproducing this issue on GitHub or JSFiddle.
Thanks!

@jimfb jimfb added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 10, 2016
@doctyper
Copy link

I am also seeing this error, particularly in unit tests that do not unmount components after the tests complete. In these cases, the value of rootNode.parentNode is null, presumably because the node is no longer attached to the DOM. The null value is then passed into getClosestInstanceFromNode, where the error is thrown due to node being null.

My current workaround is to return null if the node is null:

if (node == null) {
    return null;
}

Which seems to work, though I admittedly don't know the full consequences for doing so. I think this is at least a candidate for an invariant warning/error.

@doctyper
Copy link

I should add, this error surfaces after testing with ReactTestUtils.renderIntoDocument, which:

  1. does not have a way to unmount a test component
  2. does not attach the test component to the document

I believe this would explain why parentNode would be null.

It also returns null if the node has just been created and is not yet attached to the tree.

@jimfb
Copy link
Contributor

jimfb commented Apr 13, 2016

@nickbae91 @doctyper I am still unable to reproduce. Here is my fiddle: http://jsfiddle.net/jtxx6goy/ Can one of you provide a jsfiddle that demonstrates the issue?

@vinnymac
Copy link

vinnymac commented Apr 14, 2016

Browser

Chrome v49

OS

OS X 10.11.4

Fiddle

https://jsfiddle.net/m1hepcr3/

Summary

I actually debugged this very issue yesterday morning while trying to upgrade to v15. The solution I came up with was to provide ReactDOM with an element that already existed in the DOM via document.getElementById.

One of the projects I work on has an old backbone codebase and it has slowly been migrated to react. The element that ReactDOM was being told to render to was a div that backbone generated via document.createElement. Previously (before I upgraded to v15) this element was never being inserted into the DOM.

My stack trace revealed that getClosestInstanceFromNode had a null node as @doctyper says above. Debugging this further I discovered that ReactEventListener.js was the one calling getClosestInstanceFromNode. If you take a look at findParent you can see where the node gets defined. In my case the rootNode was an audio element that a react class was producing. The audio element had no parentNode, and so container became null.

While debugging this issue occasionally it would just disappear, and stop reporting. I would refresh a dozen times and see the error once again.

Steps to Reproduce
  1. Open Fiddle
  2. Open Console
  3. Press Run
  4. Observe mounting... logs and errors

I couldn't get it to reproduce at first. So I started spamming the run button and eventually saw the error. For the sake of everyones sanity I added a for loop that runs the code 1000 times so everyone can easily see that this does indeed reproduce the issue.

Example

EDIT 1

One thing I find interesting is if you edit the fiddle so that the audio element has no source elements, the errors do not appear. https://jsfiddle.net/g7esummj/

@jimfb
Copy link
Contributor

jimfb commented Apr 14, 2016

I have a (relatively) consistent repro in chrome: https://jsfiddle.net/r4ewebqs/

Still unable to reproduce in Firefox.

Almost looks like it might be a chrome race condition, potentially related to garbage collection, because the hit rates go way down if you spread out the calls to ReactDOM.render temporally. But the OP suggests that they've seen the failure in firefox also.

@jimfb jimfb removed the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 14, 2016
@vinnymac
Copy link

@jimfb The OP has a screenshot of the error appearing in Firefox. I attempted your fiddle as well as my own in Safari 9.1 and Firefox 45, and did not get any errors.

@nickbae91 could you provide additional information, such as the version of the browsers you tested with?

@jimfb
Copy link
Contributor

jimfb commented Apr 14, 2016

Yeah, if I upgrade from Chrome 49 (out-of-date) to Chrome 50 (latest stable), the error goes away. This is consistent with my original observation that it appeared to be a race condition potentially related to garbage collection.

I'm going to close this out as a browser bug, unless someone is able to reproduce on Chrome 50. I'd also be curious to see a firefox repro.

@jimfb jimfb added Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug and removed Type: Bug Type: Regression labels Apr 14, 2016
@zpao
Copy link
Member

zpao commented Apr 14, 2016

Let's be careful about assuming a GC issue / browser bug. We should be able to confidently say what specifically is at play. It could well be a bug in React (particularly around transactions, mounting, and local events)

My best guess here (especially since all the reports are for nodes that we have to add load / error listeners to directly) is that timing is at play. With the switch to createElement we'll actually kick off the fetching of resources earlier than before - instead of waiting for the browser to parse the img element and see src, we create the img and set src right there. That means we'll probably get a load event earlier. How early and is it possible for that event to fire before we actually attach a listener to that node is the question, and what impact does it actually have. Does it only happen on updates? Are there other events actually at play?

One thing I find interesting is if you edit the fiddle so that the audio element has no source elements, the errors do not appear

This would support my theory here as you won't get at least some of the media events.

@vinnymac
Copy link

vinnymac commented Apr 14, 2016

@jimfb I can confirm. Upgraded to Chrome 50 and I am no longer able to reproduce the issue. Hoping we can get some other reproductions of this from the OP. @nickbae91 was the only one to report seeing this elsewhere. In the meantime I'll think about a way to support @zpao's theory.

EDIT 1

@zpao I saw this error once again using Chrome v50. I was on a train and my battery was dying so I didn't have time to take a screenshot of it. I will see if I can reproduce it again, although this lends to the idea that it is timing related. I was not using our fiddles, but instead one of the closed source projects I work on. It occurred during initial page load.

EDIT 2

I finally saw the error again during startup. I have yet to debug it, but here is some proof.
Example of Error in Chrome 50

@jimfb jimfb removed the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label Apr 22, 2016
@jmullo
Copy link

jmullo commented May 25, 2016

I also bumped into something similar with unit tests running in PhantomJS 2.1.1 after upgrading to React 15.1.0. Worked fine in 0.14.8:

undefined is not an object (evaluating 'node[internalInstanceKey]')
getClosestInstanceFromNode@...
getInstanceFromNode@...

@gaearon
Copy link
Collaborator

gaearon commented May 25, 2016

Please try to provide a minimal example reproducing this.

@jmullo
Copy link

jmullo commented May 26, 2016

Seems to be some kind of timing issue, as the cases pass if I delay calls to ReactTestUtils.Simulate.focus() or ReactTestUtils.Simulate.click().

@harryhaibojiang
Copy link

harryhaibojiang commented Jun 2, 2016

I also saw this error when rendering img. But when I remove the "src" attribute in img, this error disappeared.
image

This error only exist when using npm package with webpack. Everything is OK with individual build.

@torarnek
Copy link

torarnek commented Jun 23, 2016

I can confirm that several of our mobile users on Android, using Chrome 34.0.1847, are getting this error. We are on React 15.1.0 and webpack.

Stacktrace can be found on: https://my.trackjs.com/shared/NWEwNzhlMjQ0ZGZlNDFlYmJmNjAwYWJkNTVkMWIyMzc

@jimfb
Copy link
Contributor

jimfb commented Jun 23, 2016

@torarnek There is very little we can do without a repro. If you can share the code where this is occurring, we can dig deeper. Otherwise, this is inactionable.

haibo3318 mentioned that things appeared to work with the individual builds / bower builds. Do you find the same to be true?

@gauravChaturvedi
Copy link

I'm facing the same issue, albeit for me it is occurring due to a video tag.
screen shot 2016-06-27 at 10 12 59 pm

@gauravChaturvedi
Copy link

gauravChaturvedi commented Jun 27, 2016

I was able to solve this by doing the following:

Instead of declaring my parent HTML Node inside index.html as :-

    <div id="root"></div>
    <script src="./bundle.js" type="text/javascript"></script>
</body>

I removed the div tag from index.html and added the div from my js code as follows :-

const root = document.createElement('div');
document.body.appendChild(root);
ReactDOM.render(<App />, root);

Hope this works for others as well !

@gaearon
Copy link
Collaborator

gaearon commented Jun 27, 2016

@gauravChaturvedi Can you share a minimal project that reproduces the problem?

@torarnek
Copy link

This problem was introduced by using Redux connect on various sub-components, and since this was a critical production feature, we did a quick refactoring to only connect the main component, and now it seems to be working fine.

The problem seems affect media tags when doing batch updates. See my previous stacktrace.

@destromas1
Copy link

@lyhoanglong
Why dont you use image directly inside src="../styles/images/logo.svg" something like this ?

@lyhoanglong
Copy link

@destromas1 because sometime I can reuse this image. What's wrong if I use image this way?

@ugene1213
Copy link

@lyhoanglong did you resolve your issue? I'm getting the same exact error as you and it appears every time I try to render an image

@lyhoanglong
Copy link

@ugene1213 I didnt and dont know how to fix this.

@divyanshupathak
Copy link

divyanshupathak commented Apr 24, 2017

Hi @lyhoanglong
remove import Logo from '../styles/images/logo.svg'; and try to pass the src of image or filecursor by using props from its parent component or if there is no parent component of it, then try to load the image from db and pass it in src.

@lasfin
Copy link

lasfin commented Apr 24, 2017

Got the same error (when navigate to another page of app by clicking to link). Can fix it by changing root node className, but it isn't possible in my case.

@dervalp
Copy link

dervalp commented May 11, 2017

Hi,

Got the same kind of error with an img element.

ReactDOMComponentTree.js:113 Uncaught TypeError: Cannot read property '__reactInternalInstance$c12uup2dzwt' of null

import React from 'react';
import LogoImage from './Logo.png';


const Logo = () => {
  return (
    <div>
      <img src={LogoImage} alt="Logo"/>
    </div>
  )
};

I am using url-loader but even if I am hardcoding the value of the src attribute, I get the error.

"react": "^15.5.4",
"react-dom": "^15.5.4",
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-jest": "^11.0.1",
"babel-loader": "^7.0.0",
"file-loader": "^0.11.1",
"html-webpack-plugin": "^2.28.0",
"prop-types": "^15.5.8",
"url-loader": "^0.5.8",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"

EDIT:

If I replace the image with a DIV and use the image as background, no issue. Weird stuff, as I have the impression it is something I have done for the passed 3 years without issue.

logo: {
    height: '30px',
    background: `url(${LogoImage})`,
    backgroundSize: 'contain',
    backgroundRepeat: 'no-repeat',
},

@alexandernanberg
Copy link

I hade the exact same issue, the problem for me was that I included the javascript files multiple times as @johndugan pointed out. Would it be possible for React to throw a warning if it senses that it's included multiple times?

@aeruhxi
Copy link

aeruhxi commented May 31, 2017

import React, { Component } from 'react';
import '../../assets/css/global.css';

import album from '../../assets/images/albumarts/1.jpg';

class App extends Component {
  render() {
    return (
      <div>
        <img src={album} />
      </div>
    );
  }
}

export default App;

I get the error when I try to render <img> with src in electron 1.6.10 with webpack. Image is rendered properly but I have the following error message:

Uncaught TypeError: Cannot read property '__reactInternalInstance$hxij9j4p7zw9xr0fm8fflxr' of null
    at Object.getClosestInstanceFromNode (eval at ../../node_modules/react-dom/lib/ReactDOMComponentTree.js (bundle.js:2411), <anonymous>:113:11)
    at findParent (eval at ../../node_modules/react-dom/lib/ReactEventListener.js (bundle.js:2587), <anonymous>:38:32)
    at handleTopLevelImpl (eval at ../../node_modules/react-dom/lib/ReactEventListener.js (bundle.js:2587), <anonymous>:67:28)
    at ReactDefaultBatchingStrategyTransaction.perform (eval at ../../node_modules/react-dom/lib/Transaction.js (bundle.js:2907), <anonymous>:140:20)
    at Object.batchedUpdates (eval at ../../node_modules/react-dom/lib/ReactDefaultBatchingStrategy.js (bundle.js:2539), <anonymous>:62:26)
    at Object.batchedUpdates (eval at ../../node_modules/react-dom/lib/ReactUpdates.js (bundle.js:2763), <anonymous>:97:27)
    at dispatchEvent (eval at ../../node_modules/react-dom/lib/ReactEventListener.js (bundle.js:2587), <anonymous>:147:20)

@locomotif
Copy link

locomotif commented Jun 18, 2017

I am having the same issue around the <img src=".." /> tag on a SPA.
@gaearon I have created a minimal project to reproduce the issue.

Chrome: Version 58.0.3029.110 (64-bit)

Thanks!

File structure

|-- .babelrc
|-- app
    |-- app.jsx
    |-- index.ejs
|-- package.json
|-- public
|-- webpack.config.js

app.jsx

// app.jsx
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class App extends Component {
    render() {
        return (
            <img src="https://facebook.github.io/react/img/logo.svg" />
        );
    }
}

ReactDOM.render(
    <App/> ,
    document.getElementById('container')
);

webpack.conf.js

// webpack.conf.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    context: path.resolve(__dirname, 'app'),
    entry: {
        app: './app.jsx'
    },
    output: {
        filename: 'js/[name].js',
        chunkFilename: 'js/[id].js',
        path: path.resolve(__dirname, 'public')
    },
    module: {
        rules: [
            {
                test: /\.(css|scss)$/,
                use: ExtractTextPlugin.extract({
                    use: [
                        { loader: 'css-loader' },
                        { loader: 'sass-loader' }
                    ]
                })
            },
            {
                test: /\.(js|jsx)$/,
                use: [{ loader: 'babel-loader', }],
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|svg)$/,
                use: [{ loader: 'file-loader?name=images/[name].[ext]' }]
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('css/[name].css'),
        new webpack.HotModuleReplacementPlugin(),
        new HtmlWebpackPlugin({
            template: 'index.ejs'
        })
    ]
};

.babelrc

{
    "presets":[ 
        "es2015",
        "react"
    ],
    "plugins":[
        "transform-object-rest-spread"
    ]
}  

package.json

{
  "name": "example",
  "version": "0.0.1",
  "description": "img src issue",
  "scripts": {
    "start": "webpack-dev-server",
    "build": "webpack"
  },
  "devDependencies": {
    "babel-core": "^6.25.0",
    "babel-loader": "^7.0.0",
    "babel-plugin-transform-object-rest-spread": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "file-loader": "^0.11.2",
    "html-webpack-plugin": "^2.28.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "scss-loader": "^0.0.1",
    "webpack": "^2.6.1",
    "webpack-dev-server": "^2.4.5"
  },
  "dependencies": {}
}

index.ejs

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Img src issue</title>
  </head>
  <body>
    <div id="container"></div>
    <script src="/js/app.js"></script>
  </body>
</html>

@locomotif
Copy link

locomotif commented Jun 18, 2017

Also, I confirmed @doctyper findings that rootNode.parentNode is null. I did a similar workaround in react-dom/lib/ReactEventListner.js , function findParent(). I added the following, just so that I can bypass the error:

  if (container) {
      return ReactDOMComponentTree.getClosestInstanceFromNode(container);
  } else {
      return null;
  }

I am just beginning to learn react, so I am not sure exactly what is happening and why there is a unmounted node looking for a parent.

@cdaringe
Copy link

I haven't pin-pointed it, but i'm with @locomotif--for me the single change that either creates or eliminates the failure is the src attribute on the image tag.

it's not a minimum viable example, but it is rather small--almost === CRA barebones. if one:

  • clones this snapshot
  • runs yarn && yarn start, you can see the error
  • fiddle with the <App /> component's image to see it get weird.

@cdaringe
Copy link

it appears that rootNode isn't guaranteed to be mounted on the DOM after calling getNodeFromInstance from within findParent.

consequently, sniffing for rootNode's .parentNode yields null.

screen shot 2017-06-18 at 8 15 24 pm

missing from above, rootNode.id === 'id'

@alexandernanberg
Copy link

@locomotif You are having the same problem that I was dealing with. Just remove the <script> tag in your index.ejs file and it should work as expected. The issue is that you are including your script files 2 times. You could also set HtmlWebpackPlugin to not automatically include your assets if you want to do that in your template.

@locomotif
Copy link

locomotif commented Jun 19, 2017

@alexandernanberg That makes absolute sense! thanks, that did the trick! I had just recently added the html-webpack-plugin, and it didn't occur to me to remove that line of code. I had noticed that my console message was appearing twice, and briefly assumed that something was being loaded twice; but then I disregarded it and thought it had to do with the hot loader. Not until I added the image node a couple of days after did this issue exposed itself. Thanks a million, I don't think I would have thought to look there since the index.ejs was not in my radar.

I also should have read @johndugan post, I guess I must have missed it.

@jeantimex
Copy link

I was experiencing the same issue as @haibo3318 did. At first glance, the src attribute looks suspicious, because everything works fine after removing the src attribute from the img tag. Then I took another look into the html content, I found this:

<script src="main.js" ... />
<script src="main.js" ... />

In my case, I have two little separate React widgets on the page, and they are embedded by the same php template in which the script tag is included. This caused the Uncaught TypeError: Cannot read property '__reactInternalInstance$... error!

The way I fixed this problem is just making sure the script tag is included only once.

@soundobj
Copy link

soundobj commented Aug 10, 2017

This is still happening on Chrome Version 60.0.3112.90 (Official Build) (64-bit) and react 15.6.1 on Windows.

ReactDOM.render(
   <img src="https://ichef.bbci.co.uk/news/660/cpsprodpb/23A5/production/_97252190_markgraf.jpg" />,
  document.querySelector('#yourSelector'),
);

no duplicate react AFAIK.

Uncaught TypeError: Cannot read property '__reactInternalInstance$

On my particular example the culprit are tags. if i remove the src attribute on the images then the error goes away. Firefox is fine on the same machine as OSX / Chrome so it seems a browser / OS specific issue.

@gaearon
Copy link
Collaborator

gaearon commented Aug 10, 2017

If you can reproduce this please attach a reproducible example. Just saying "I have this too" is not very helpful because it does not help us understand the problem, and does not guarantee you have excluded known causes (such as duplicate React).

cwikla pushed a commit to cwikla/cruitz that referenced this issue Aug 24, 2017
@colindekker
Copy link

Have this issue now, here is a bare bones SPfx project, including the React draftjs wysiwyg component. Works fine on chrome, IE11 and Edge the load fails. run gulp serve to load the SPfx workbench, after it loads, click the little plus at the top of the page and select RteEditor to add the component in the workbench and it will fail. Project: https://drive.google.com/file/d/0BxopWiNF_Y9zWmFPYk5IaEFZNms/view?usp=sharing

@WGLayner
Copy link

WGLayner commented Sep 25, 2017

I met the same problem with below code. The problem is not there after remove img tag.

<Navbar.Header> <Navbar.Brand> <a href="#"> <img src="/images/cp1.png" alt="logo" style={logoStyle} /> </a> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header>

@colindekker
Copy link

colindekker commented Sep 25, 2017 via email

@gaearon
Copy link
Collaborator

gaearon commented Oct 3, 2017

In the vast majority of cases this error was caught by an earlier error in the application code that got swallowed by some third-party library (or application code).

React 16 should surface the original error better in this case so I’m closing. If you still experience this after upgrading to React 16 please file a new issue with a complete reproducing example.

@gaearon gaearon closed this as completed Oct 3, 2017
@tkssharma
Copy link

one possible solution is you just need to make sure if you have multiple instances loaded in you index.html of react. I was getting it because i have added webpack bundle twice while running it using webpack-dev-server with htmlwebpack plugin.

now fixed !! :)

@chaituckr
Copy link

This issue is also occurs when we dont import the child/third party components and use them in the current component. So, make sure you imported all the components that are being used in current component.

@cancerberoSgx
Copy link

cancerberoSgx commented Feb 18, 2019

this happens to me for some reason too, probably because my component is being updated multiple times and the wrapper instance is old. Calling wrapper.update() before simulate() solves the problam. Or also checking like this:

wrapper.filterWhere(w=>w && w.getDOMNode()) .forEach(w=>
    w.simulate('click', ...

w.parent() is not enough for me. Would be nice to have a predicate method to see if the wrapper instance is obsolete so we know we should call update()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests