react icon indicating copy to clipboard operation
react copied to clipboard

Bug: The invalid value warning was showed when adding functions to object prototype

Open virtuous-code opened this issue 4 years ago • 2 comments

While adding a function to Object.prototype in React project anywhere, react while showing the Warning: Invalid value for prop `xxx` on tag. And an uncaught TypeError.

React version: 17.0.2

Steps To Reproduce

  1. Create a react project with create-react-app
  2. Put the following code anywhere in the project: Object.prototype.test = function () {} 图片

The current behavior

Getting the warning 图片 Also the Uncaught TypeError: renderer.setTraceUpdatesEnabled is not a function. 图片

The expected behavior

Expected nether warning nor error.

virtuous-code avatar Mar 25 '21 06:03 virtuous-code

Object.prototype.test = function () {}

This adds an enumerable property to every object in your entire JS context. In a normal JS environment, this is not the case; for instance, { a: 3, b: 4 } has exactly two enumerable properties normally, "a", and "b".

You probably shouldn't make this change. Even if the React team is willing to support it, many other libraries will assume you haven't mucked up Object.prototype with extra enumerable junk. for .. in loops oftentimes don't have own property guards on them because in a regular JS environment, you don't need them.

If you absolutely have to do this, you should make the property non-enumerable.

nmain avatar Apr 22 '21 12:04 nmain

Thanks for the that save me a lot of time!

Sinieghi avatar Dec 14 '23 15:12 Sinieghi

Yeah patching the object prototype isn't supported.

rickhanlonii avatar Feb 11 '24 15:02 rickhanlonii