Javascript: Cannot assign to read only property '_epoch' of false

robert king picture robert king · Oct 16, 2014 · Viewed 18.1k times · Source

I have a method to process the response from my google javascript client (gapi):

var processResponse = function(response) {
              result._state = 'loaded';
              response._epoch = (new Date()).getTime();
              ...

A few times I have gotten the following error:

TypeError: Cannot assign to read only property '_epoch' of false
    at processResponse (http://0.0.0.0:9000/scripts/services/haparaapi.js:110:31)
    at wrappedCallback (http://0.0.0.0:9000/bower_components/angular-scenario/angular-scenario.js:20892:81)
    at http://0.0.0.0:9000/bower_components/angular-scenario/angular-scenario.js:20978:26
    at Scope.$eval (http://0.0.0.0:9000/bower_components/angular-scenario/angular-scenario.js:21967:28)
    at Scope.$digest (http://0.0.0.0:9000/bower_components/angular-scenario/angular-scenario.js:21796:31)
    at Scope.$apply (http://0.0.0.0:9000/bower_components/angular-scenario/angular-scenario.js:22071:24)
    at http://0.0.0.0:9000/bower_components/angular-gapi/modules/gapi-client.js:121:32
    at https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en_GB.hE_reuZ6VdE.…/ed=1/am=AQ/rs=AGLTcCPj66Crj6soG8dKJE8lBSc_RPXXKA/cb=gapi.loaded_0:604:138
    at https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en_GB.hE_reuZ6VdE.…/ed=1/am=AQ/rs=AGLTcCPj66Crj6soG8dKJE8lBSc_RPXXKA/cb=gapi.loaded_0:579:311
    at Object.<anonymous> (https://apis.google.com/_/scs/apps-static/_/js/k=oz.gapi.en_GB.hE_reuZ6VdE.…1/ed=1/am=AQ/rs=AGLTcCPj66Crj6soG8dKJE8lBSc_RPXXKA/cb=gapi.loaded_0:163:76) 

This bug doesn't usually happen so I haven't managed to log what the response actually looked like.

What does the error mean? Should I not be assigning values to the response?

Answer

itsmejodie picture itsmejodie · Oct 21, 2014

It looks like the issue is that your processResponse() callback is actually being given a value of false. So essentially you are trying to assign the _epoch property of a false value.

See: https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientRequest

From the manual:

The callback function which executes when the request succeeds or fails. jsonResp contains the response parsed as JSON. If the response is not JSON, this field will be false.

When you're running javascript in strict mode ('use strict'), it will raise a TypeError like you are experiencing:

'use strict';
var processResponse = function(response) {
    response._epoch = (new Date()).getTime();
};

processResponse(false);   // Uncaught TypeError: Cannot assign to read only property '_epoch' of false 

JSFiddle: http://jsfiddle.net/0tq6mobm/

Suggest that you check the value of response before trying to assign your timestamp to the response.