The basement battle, which was effectively a winner takes all contest, burst into life in the second half.
Mansfield - with just one point in that long run of 11 home games without a win - looked to be in control when Jefferson Louis converted a penalty and Johnny Mullins quickly added a second.
But the Stags, looking for their first home win since Boxing Day, were made to hang on in four long minutes of injury time after Mark Williams scored 12 minutes from the end.
Wrexham had created the better chances in an even and scrappy first half.
In the 11th minute Paul Hall found Drewe Broughton and his angled shot went straight at Carl Muggleton. The striker had earlier sent a dipping 25-yard drive over.
Then Phil Bolland nodded just wide at the far post from Hall's corner, before Muggleton grabbed the ball bravely as Stuart Nicholson tried to get on the end of a through ball.
Wrexham continued to look the more dangerous, when Llewellyn smashed a low 20 yard drive wide and Hall drove over from 18 yards.
For the Stags, Mick Boulding headed straight at keeper Gavin Ward from a Matt Hamshaw cross early on.
But Town burst into goalmouth action at the start of the second half to grab the vital two-goal advantage.
First Wrexham's Gareth Evans handled to concede a penalty after feeling he had been fouled himself. Wrexham protested the wind had blown the ball off the spot, but Louis kept his nerve to open the scoring with the 51st minute penalty.
Michael Boulding immediately volleyed over from Mullins' flick but within four minutes of Louis' breakthrough the Stags had doubled their lead.
Hamshaw's reverse pass found Mullins running into the area and the full-back fired under Ward.
Yet the Stags were almost made to pay for not finishing the Dragons off when the visitors grabbed a lifeline through Marc Williams, firing in after Muggleton did well to save Nicholson's drive.
Wrexham failed to create another chance and the Stags almost regained their two-goal advantage when Stephen Dawson burst into the area. His shot was blocked by Ward and Simon Spender did well to prevent Boulding's follow-up finding the net.