Мы используем рендеринг на стороне сервера с GraalVM. Приложение выдает ошибку ниже
org.graalvm.polyglot.PolyglotException: TypeError: <this>.clearProviders is not a function
at <js>.b.destroy(propertysrp.js:1566)
at <js>.renderToString(propertysrp.js:1566)
Я проверил исходный репозиторий React на GitHub и обнаружил, что в файле ReactPartialRenderer.js функцияclearProviders определена в строке номер 821, мы используем веб-пакет для объединения JS, вызов функцииclearProviders происходит из Destruct. () из строки номер 757, оба упомянуты в одном файле, тогда почему определениеclearProviders отсутствует в комплекте JS
вот фрагмент файла, в котором упоминается вызов функцииclearProviders, но фактическое определение отсутствует во всем файле, в каком сценарии это происходит, все работает нормально, мы не вносили никаких изменений для реагирования на управление версиями, мы просто пересобираем приложение через некоторое время небольшие изменения и появились ошибки
,t.version = "16.14.0"},function(e,t,r){
/** @license React v16.14.0
* react-dom-server.browser.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var n=r(110),o=r(0);function i(e){for(var t = "https://reactjs.org/docs/error-decoder.html?invariant = "+e,r=1;r<arguments.length;r++)t+ = "&args[] = "+encodeURIComponent(arguments[r]);return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var a=((r = "function"==typeof Symbol&&Symbol.for)&&Symbol.for("react.portal"),r?Symbol.for("react.fragment"):60107);r&&Symbol.for("react.strict_mode"),r&&Symbol.for("react.profiler"),r&&Symbol.for("react.provider"),r&&Symbol.for("react.context"),r&&Symbol.for("react.concurrent_mode"),r&&Symbol.for("react.forward_ref"),r&&Symbol.for("react.suspense"),r&&Symbol.for("react.suspense_list"),r&&Symbol.for("react.memo"),r&&Symbol.for("react.lazy"),r&&Symbol.for("react.block"),r&&Symbol.for("react.fundamental"),r&&Symbol.for("react.scope");for(var c=((r=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED).hasOwnProperty("ReactCurrentDispatcher")||(r.ReactCurrentDispatcher = {current:null}),r.hasOwnProperty("ReactCurrentBatchConfig")||(r.ReactCurrentBatchConfig = {suspense:null}),{}),l=new Uint16Array(16),u=0;u<15;u++)l[u]=u+1;l[15]=0,Object.prototype.hasOwnProperty,"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){e[0]})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){e.toLowerCase()})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){})),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){e.toLowerCase()})),["checked","multiple","muted","selected"].forEach((function(e){})),["capture","download"].forEach((function(e){})),["cols","rows","size","span"].forEach((function(e){})),["rowSpan","start"].forEach((function(e){e.toLowerCase()}));var s=/[\-:]([a-z])/g;function f(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){e.replace(s,f)})),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){e.replace(s,f)})),["xml:base","xml:lang","xml:space"].forEach((function(e){e.replace(s,f)})),["tabIndex","crossOrigin"].forEach((function(e){e.toLowerCase()})),["src","href","action","formAction"].forEach((function(e){e.toLowerCase()})),Object.is;var p=(n({menuitem:!0},m = {area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}),{animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0}),d=["Webkit","ms","Moz","O"],y=(Object.keys(p).forEach((function(e){d.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),p[t]=p[e]}))})),o.Children.toArray);r.ReactCurrentDispatcher,Object.prototype.hasOwnProperty,g.prototype.destroy=function(){var e;this.exhausted||(this.exhausted=!0,this.clearProviders(),e=this.threadID,l[e]=l[0],l[0]=e)};var h=g,m = {renderToString:function(e){e=new h(e,!1);try{return e.read(1/0)}finally{e.destroy()}},renderToStaticMarkup:function(e){e=new h(e,!0);try{return e.read(1/0)}finally{e.destroy()}},renderToNodeStream:function(){throw Error(i(207))},renderToStaticNodeStream:function(){throw Error(i(208))},version:"16.14.0"};function g(e,t){if (e = {type:null,domNamespace:"http://www.w3.org/1999/xhtml",children:e=o.isValidElement(e)&&(e.type!==a||(e=e.props.children,o.isValidElement(e)))?[e]:y(e),childIndex:0,context:c,footer:""},0===(r=l[0])){var r,n=l,u=2*(r=n.length);if (!(u<=65536))throw Error(i(304));var s=new Uint16Array(u);for(s.set(n),(l=s)[0]=r+1,n=r;n<u-1;n++)l[n]=n+1;l[u-1]=0}else l[0]=l[r];this.threadID=r,this.stack=[e],this.exhausted=!1,this.currentSelectValue=null,this.previousWasTextNode=!1,this.makeStaticMarkup=t,this.suspenseDepth=0,this.contextIndex=-1,this.contextStack=[],this.contextValueStack=[]}e.exports=m.default||m},function(e,t,r){
вот конфигурация веб-пакета
function serverComponentEntry (componentName) {
return {
devtool: 'source-map',
mode: 'development',
entry: `./react-src/${componentName}/${componentName}-server.js`,
output: {
filename: `${componentName}.js`,
path: path.resolve(__dirname, OUTPUT_PATH + '/' + TARGET_SERVER)
},
plugins: [
new CleanWebpackPlugin([TARGET_SERVER], {
root: BASE_PATH + '/' + OUTPUT_PATH
}),
new UglifyJsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('release')
}
}),
new DotenvCmdWebpack({filePath: ENV_FILE_PATH, env: "constant"})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.svg$/,
loader: 'null-loader'
},
{
test: /\.(ttf|eot|woff2?)$/,
loader: 'null-loader'
}
]
}
}
}
const markup = ReactDOMServer.renderToString(
<StaticRouter>
<Provider store = {store1}>
<App/>
</Provider>
</StaticRouter>
);
в нашем package.json это версия, которую мы используем для реагирования и реагирования-дома.
"react-dom": "16.14.0",
"react": "16.14.0",
Итак, проблема была с UglifyJsPlugin, его заменили плагином terser webpack
решил это, я не уверен, в чем была основная причина, почему uglifyJsPlugin до сих пор работал нормально и внезапно выдал эту ошибку, мы использовали последнюю версию "uglifyjs-webpack-plugin": "^2.2.0"