The Hammers twice had to come from behind, with Manuel Lanzini cancelling out Thiago Silva’s header, before Jarrod Bowen put the hosts back on terms after Mason Mount’s wonderful volley.
But just as it looked like it was heading for a draw at the London Stadium, Masuaku’s cross somehow beat Mendy at his near post and flew into the top corner, to give David Moyes’ side a memorable win.
Both sides offered a threat going forward in the early stages, but it was Chelsea who took the lead.
Silva headed in from a Mount corner, with Lukasz Fabianski getting a hand on it but the goalkeeper was unable to keep it out.
A minute later, Silva was on hand at the other end of the pitch, clearly a Coufal shot off the line brilliantly to deny West Ham.
Edouard Mendy then gifted the Hammers a way back into it. Jorginho’s backpass was poor, and Mendy delayed before losing the ball and then bringing down Bowen. Lanzini stepped up from the spot and put his side level.
But Chelsea went into the break ahead. Hakim Ziyech floated a crossfield switch to Mount, who cushioned a sublime volley past Fabianski at the near post.
Ten minutes into the second-half, Bowen equalised for the Hammers. Vladimir Coufal poked the ball inside, and Bowen produced a brilliant curling finish into the far corner.
Kurt Zouma limped off for West Ham, to add to their injury woes at the back following Angelo Ogbonna’s long-term absence.
The hosts very nearly took the lead with 15 minutes remaining. Antonio played a ball across the face of goal, and Bowen couldn’t quite divert it into the empty net from a few yards out as he slid in.
But West Ham got their winner with just three minutes remaining. Masuaku sent a left-footed cross into the box, and it beat a scrambling Mendy at his near post, much to the delight of a raucous London Stadium.
It means West Ham will finish the weekend in the top four, while Chelsea could now lose their spot at the top of the table.